cloudflare / cloudflare/chanfana
Is is possible to access `data.body` when using middlewares?
- Dominant language
- TypeScript
- Stars
- 766
- Forks
- 70
- Avg merge
- 25m
- Merged PRs (30d)
- 4
Description
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 with `request`.
`index.js`
```js
import { OpenAPIRouter } from "@cloudflare/itty-router-openapi";
import { SignUp } from "./Users/controller";
import isValidEmail from "./utils/email"
const router = OpenAPIRouter({
schema: {
info: {
title: "Worker OpenAPI Example",
version: "1.0",
},
},
});
router.post("/api/users", isValidEmail, SignUp)
// Redirect root request to the /docs page
router.original.get("/", (request) =>
Response.redirect(`${request.url}docs`, 302)
);
// 404 for everything else
router.all("*", () => new Response("Not Found.", { status: 404 }));
export default {
fetch: router.handle,
};
```
`./utils/email.js`
```js
const EMAIL_REGEXP = new RegExp(
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
);
const isValidEmail = (request,
env,
context,
data) => {
console.log(data)
return EMAIL_REGEXP.test(data.body.email);
}
export default isValidEmail
```
`./users/controller.js`
```js
import {
Bool,
OpenAPIRoute,
Path,
Str
} from "@cloudflare/itty-router-openapi";
import isValidEmail from "../utils/email"
const SignUpResponse = {
message: "User Added!"
}
export class SignUp extends OpenAPIRoute {
static schema = {
tags: ["Users"],
summary: "User Sign Up",
requestBody: {
contentType: 'application/json',
firstname: new Str({
description: "User Firstname",
required: true,
example: "Ashish"
}),
lastname: new Str({
description: "User Lastname",
required: true,
example: "Jullia"
}),
email: new Str({
description: "User Email",
required: true,
example: "username@example.com"
}),
password: new Str({
description: "User Password",
required: true,
example: "As@121212121212"
})
},
responses: {
"200": {
contentType: 'application/json',
schema: {
Response: SignUpResponse,
},
},
},
};
async handle(
request,
env,
context,
data
) {
// Retrieve the validated slug
const { firstname, lastname, email, password } = data.body
// console.log(isValidEmail(email))
return {
message: "User Added!"
};
}
}
```
Contributor guide
Research direction
Start with index.js, utils/email.js, and users/controller.js, then trace how the middleware arguments and OpenAPIRoute handle arguments are assembled. Verify whether data.body is available in isValidEmail and compare it with the shape consumed by SignUp; done means the supported behavior and required data access are clear and reproducible.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- openapi, typescript
- Domain
- api
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100