-
I'm just starting to play around with orpc and its amazing getting things up and running so quickly - thanks for your hard work! I'm using contract first development approach with open API and using scalar to render things, this is all appears to be working. Can we allow middleware to update openapi spec regarding errors/responses? contractexport const PlanetSchema = z.object({
id: z.number().int().min(1),
name: z.string(),
description: z.string().optional(),
})
export const planetsContract = oc
.router({
list: oc
.route({ method: 'GET', path: '/planets', description: "get a list of planets" })
.input(
z.object({
limit: z.number().int().min(1).max(100).optional(),
cursor: z.number().int().min(0).default(0),
}),
)
.output(z.array(PlanetSchema)),
find: oc
.route({ method: 'GET', path: '/planets/{id}', description: "get a planet" })
.input(PlanetSchema.pick({ id: true }))
.output(PlanetSchema),
create: oc
.route({ method: 'PUT', path: '/planets', description: "create a planet" })
// Adding this has the desired affect
//
// .errors({
// UNAUTHORIZED: oo.spec({}, {
// security: authDocs.security
// })
// })
.input(PlanetSchema.omit({ id: true }))
.output(PlanetSchema)
}) routerconst os = createRouter(planetsContract) // <-- Ensures Context type is set: implement<typeof contract, Context>(contract)
export const planetsRouter = os
.router({
list: os.list
.handler(({ input }) => {
return [{ id: 123, name: "Planet X" }]
}),
find: os.find
.handler(({ input }) => {
return { id: 123, name: 'Planet X' }
}),
create: os.create
.use(requireAuth)
.handler(({ input }) => {
return { id: 123, name: 'Planet X' }
})
}) openapi specconst openAPIGenerator = new OpenAPIGenerator({
schemaConverters: [
new ZodToJsonSchemaConverter(),
],
})
const apiSpec = await openAPIGenerator.generate(planetsContract, {
info: {
title: 'My App',
version: '0.0.0',
},
}),
components: {
securitySchemes: authDocs.securitySchemes
}
}) require authexport const requireAuth = os
.$context<Context>()
.errors({
UNAUTHORIZED: oo.spec({}, {
security: authDocs.security // <-- This doesnt have any affect
})
})
.middleware(async ({ context, next, errors }) => {
if (!context.user) throw errors.UNAUTHORIZED()
return next()
}) With the above code, the generated responses for Using Is there a way to work around this? While also maintaining type safe errors on the client? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You can reduce duplication when defining import { oc } from '@orpc/contract'
const publicContractBuilder = oc
const authedContractBuilder = publicContractBuilder.errors({
UNAUTHORIZED: oo.spec({}, {
security: authDocs.security
})
}) Now, any contract built using |
Beta Was this translation helpful? Give feedback.
You can reduce duplication when defining
oo.spec()
like this:Now, any contract built using
authedContractBuilder
will automatically include theUNAUTHORIZED
error and applyauthDocs.security
as its security scheme.