Last active
February 15, 2024 01:36
-
-
Save razor-x/2f8c4b85baa6c1df8dadf746cc7ae8ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { Middleware, createWithEdgeSpec } from 'edgespec' | |
const users: Record<string, { userId }> = { | |
fake_api_key1: { userId: 'fake-user-id-1' }, | |
} | |
const withApiKey: Middleware = (req, ctx, next) => { | |
const apiKey = req.headers.get('authorization').split('Bearer ') | |
req.user = users[apiKey] | |
return next() | |
} | |
const withAppContext: Middleware = (req, ctx, next) => { | |
req.app = { | |
log: pino(), | |
} | |
return next() | |
} | |
const withSecurityHeaders: Middleware = (req, ctx, next) => { | |
ctx.defaultResponse = ctx.defaultResponse.setHeader( | |
'x-content-type-options', | |
'nosniff', | |
) | |
return next(req, ctx) | |
} | |
const withUserId: Middleware = (req, ctx, next) => { | |
ctx.defaultResponse = ctx.defaultResponse.setHeader( | |
'user-id', | |
req.user?.userId, | |
) | |
return next() | |
} | |
const withResponseLogging: Middleware = (req, ctx, next) => { | |
const res = await next() | |
const responseTime = res.headers.get('') | |
ctx.app.log({ method: ctx.method, url: req.url, responseTime }, 'Response') | |
} | |
const withResponseTime: Middleware = (req, ctx, next) => { | |
const start = Date.now() | |
const res = await next() | |
const ms = Date.now() - start | |
return res.setHeader('x-response-time', `${ms}ms`) | |
} | |
const withEdgeSpec = createWithEdgeSpec({ | |
authMiddleware: { | |
api_key: withApiKey, | |
}, | |
beforeAuthMiddleware: [ | |
withAppContext, | |
withSecurityHeaders, | |
withResponseTime, | |
withResponseLogging, | |
], | |
afterAuthMiddleware: [withUserId], | |
}) | |
export default withEdgeSpec({ | |
auth: ['api_key'], | |
methods: ['POST'], | |
jsonBody: z.object({ | |
a: z.number(), | |
b: z.number(), | |
}), | |
jsonResponse: z.object({ | |
sum: z.number(), | |
}), | |
})((req) => { | |
const { a, b } = await req.json() | |
return ctx | |
.status(200) | |
.setHeader('foo', 'bar') | |
.json({ | |
sum: a + b, | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment