-
-
Notifications
You must be signed in to change notification settings - Fork 0
Type Safe
- How To Type Safe My Code?
- How To Create a Type Safe Action?
- How To Create a Type Safe Event?
- How To Create a Type Safe Action/Event Call?
In Busy Hour we really love TypeScript and make sure our code is type safe as much as possible. Therefore, we try to make blaze as type safe as possible by creating a @busy-hour/blaze-types to help creating type safe action
and events
call. We also add support for auto OpenAPI
documentation since v1.1.0 which also supports @hono/swagger-ui
middleware.
To create a Type Safe Action, you can start by importing Action
or BlazeCreator
and zod from @busy-hour/blaze
.
import { BlazeCreator, z } from '@busy-hour/blaze'
After you import BlazeCreator
, you can start creating your own type safe action by using the satisfies Action
keyword and pass the properties that you need.
const createUser = BlazeCreator.action({
openapi: {
// Add this to auto start documenting your REST API OpenAPI
// The `body` are only to define the type of allowed user payload
},
validator: {
// Add this to auto validate your REST API/Internal API call through context API
// Must be a `zod` object from `@busy-hour/blaze`
},
rest: {
// Add this to allow REST API
},
hooks: {
// Add the hooks if you need to
},
async handler(ctx) {
// Do something
}
})
In case you feel like some need of the hooks
, validator
, and openapi
object can be reuse for another action, you can create them separately by using the same method of creating the action by importing AcceptedBeforeHook
, AcceptedAfterHook
, ActionValidator
, and ActionOpenAPI
.
const userOpenapi = BlazeCreator.action.openapi({
type: 'application/json',
required: true,
})
const userValidator = BlazeCreator.action.validator({
// Add this to auto validate your Internal API call through context API
// Must be a `zod` object from `@busy-hour/blaze`
})
const userCreateAfterHook = BlazeCreator.action.hook.after((ctx, res) => { // You can add the type for `res` in case you don't want it to be `unknown`
// Do something
return res // make sure to return something
})
const userCreatedBeforeHook = BlazeCreator.action.hook.before((ctx) => {
// Do something
})
Same as how you create a type safe action, you can also create a type safe event by using by using the satisfies Event
keyword.
const onUserCreated = BlazeCreator.event({
// Add this to auto validate your Internal API call through context API
// Must be a `zod` object from `@busy-hour/blaze`
validator: null,
async handler(ctx) {
// Do something
}
})
To create a type safe action/event call, you can read more the detail by reading it more on our TypeScript plugin wiki (@busy-hour/blaze-types).