Closed PlayWolfYT closed 1 year ago
Why you cant use builtin use
method for that?
auth.ts
export function auth(res, res, next) {
...
}
protected/admin.ts
export { auth as default } from "./auth.ts";
export function GET(req, res, next) {
...
}
(Assuming that in in plugin settings mapper has 'default': 'use', example)
Well you can use the use
method, that is correct, but that would only allow for a single middleware to be used. With this PR it would allow for any number of middlewares which can be chained.
For example:
Code-Example:
// Example-File: /api/users.ts
import { authenticationMiddleware } from './authenticationMiddleware';
import { authorizationMiddleware } from './authorizationMiddleware';
import { bodyValidationMiddleware } from './zodBodyValidation';
export const MIDDLEWARES = [
authenticationMiddleware,
authorizationMiddleware,
bodyValidationMiddleware<UserCreateBody>
]
type UserCreateBody {
username: string;
password: string;
}
Ok, at first I also thought about that possibility and in this case I think the best solution is export an array of functions.
const authorizationMiddleware = (req, res, next) => {
req.authData = {
message: "Authorization Middleware Security",
};
next();
};
const sessionMiddleware = (req, res, next) => {
req.sessionData = {
message: "Session Middleware Restore",
};
next();
};
const paramObjectMiddleware = (req, res, next) => {
req.paramObject = {
message: "ParamObject Middleware, ParamNames to Object",
};
next();
};
export default [
authorizationMiddleware,
sessionMiddleware,
paramObjectMiddleware,
];
I this case, we need change the appplyRouters
applyRouters(
(props) => {
const { method, route, path, cb } = props;
if (handler[method]) {
if(Array.isArray(cb)){
// for the route we apply the array function as middleware
handler[method](route, ...cb);
} else {
handler[method](route, cb);
}
} else {
console.log("Not Support", method, "for", route, "in", handler);
}
}
);
I think it will be the best solution because the POST, GET and others function would inherit this strategy.
@PlayWolfYT If could changes your PR with this definition, I will merge and release the new version
Sure thing, will do it on monday as I don't have time on this sunday, but i'll let you know when the changes are ready 👍
Adds functionality for per-route middlewares. This can be used for authentication and similar.
Added additional route
example/src/api/admin/auth/protected.ts
(/api/admin/auth/protected) to show how the middlewares can be used for authentication.Also updated the README, since it contained dead links (example server.js and handler.js files did not exist).
Created two example files for
server.ts
andhandler.ts
Note: I updated the
example/src/api/admin/auth/login.ts
file to actually have a working login example.