Open ashishjullia opened 1 year ago
Also, the contentType: 'application/json'
is not working for requestBody
, not sure how to pass it correctly.
I've an issue opened for confirmation: https://github.com/cloudflare/itty-router-openapi/issues/85
With a framework like expressjs
(out of context of cf workers) which provides you (req, res, next) and makes it easier to follow middleware pattern and extracting say (email key) from body as req.body.email
.
Is is possible to achieve the same with this itty-rotuer-openapi
? I'm aware that it has (request, env, context, data)
but unable to get the data.body.email
and next
in the similar fashion :/
Hey there, in order to validate emails you should use the Email
type like this:
import {
Email
} from "@cloudflare/itty-router-openapi";
...
email: new Email({
description: "User Email",
required: true,
}),
Currently middleware support is limited, and you cannot access the data
object, you can read more about whats supported here
itty-router-openapi doesn't support the next()
function like express, but you should be able to modify the request, env, context
parameters in middlewares and these changes will be applied in downstream endpoints
@G4brym
Hmm, thanks for the information but by providing the email example I wanted to know whether how to play on data.body
when working with middleware because a lot of powerful things like authentication/authorization can be done via these middlewares or more such things.
Sad to know that it won't be possible with this. :/
You can do middlewares the "old fashion", because the endpoints are all class based, you can just build a base class that does authentication and then extend your endpoint from there.
otherwise you can still do authentication with the current middleware support here is a snipped taken from here
export function getBearer(request: Request): null | string {
const authHeader = request.headers.get('Authorization')
if (!authHeader || authHeader.substring(0, 6) !== 'Bearer') {
return null
}
return authHeader.substring(6).trim()
}
export async function authenticateUser(request: Request, env: any, context: any) {
const token = getBearer(request)
let session
if (token) {
session = await context.qb.fetchOne({
tableName: 'users_sessions',
fields: '*',
where: {
conditions: [
'token = ?1',
'expires_at > ?2',
],
params: [
token,
new Date().getTime()
]
},
}).execute()
}
if (!token || !session.results) {
return new Response(JSON.stringify({
success: false,
errors: "Authentication error"
}), {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
status: 401,
})
}
// set the user_id for endpoint routes to be able to reference it
env.user_id = session.results.user_id
}
...
// Authentication middleware
router.all('/api/*', authenticateUser)
Hi,
I've the following code in which I'm trying to run a middleware on
data.body.email
but unable to do so, am I missing something or is it just possible withrequest
.index.js
./utils/email.js
./users/controller.js