Replace legacy checkBodyType with Zod
Start matchmaking integration Start rooms API Move existing room scene locations to roomtypes file Auth checkExpired util for client refreshing
This commit is contained in:
@@ -5,6 +5,7 @@ import { decode } from "@gz/jwt";
|
||||
import { Config } from "./config.ts";
|
||||
import { AuthType, User, UserTokenFormat } from "./data/users.ts";
|
||||
import Profile, { ProfileTokenFormat } from "./data/profiles.ts";
|
||||
import z from "zod";
|
||||
|
||||
const config = Config.getConfig();
|
||||
|
||||
@@ -57,43 +58,40 @@ export function checkQueryTypes<T>(typeDef: T) {
|
||||
nxt();
|
||||
};
|
||||
}
|
||||
export function checkBodyTypes<T>(typeDef: T) {
|
||||
return (
|
||||
rq: express.Request,
|
||||
rs: express.Response,
|
||||
nxt: express.NextFunction,
|
||||
) => {
|
||||
for (const key in typeDef) {
|
||||
if (typeof rq.body[key] !== typeof typeDef[key]) {
|
||||
log.e(`Body check for key '${key}' failed.`);
|
||||
rs.statusCode = 400;
|
||||
rs.json(
|
||||
genericResponseFormat(
|
||||
true,
|
||||
"One or more body values were invalid or not found.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export const validateRequestBody = <T>(schema: z.ZodSchema<T>) => (rq: express.Request, rs: express.Response, nxt: express.NextFunction) => {
|
||||
try {
|
||||
schema.parse(rq.body);
|
||||
nxt();
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError)
|
||||
rs.status(400).json(genericResponseFormat(true, "Bad request", undefined, error.errors));
|
||||
}
|
||||
};
|
||||
|
||||
type genericResponse = {
|
||||
failure: boolean,
|
||||
errors?: object, // zod only
|
||||
message?: string,
|
||||
data?: object
|
||||
}
|
||||
|
||||
export function genericResponseFormat(
|
||||
failure: boolean,
|
||||
msg: string | null = null,
|
||||
data: object | null = null,
|
||||
msg?: string,
|
||||
data?: object,
|
||||
errors?: object,
|
||||
) {
|
||||
return { failed: failure, message: msg, data: data };
|
||||
return { failure: failure, errors: errors, message: msg, data: data } as genericResponse;
|
||||
}
|
||||
export function genericResponse(
|
||||
failure: boolean,
|
||||
msg: string | null = null,
|
||||
data: object | null = null,
|
||||
msg?: string,
|
||||
data?: object,
|
||||
errors?: z.ZodError[],
|
||||
) {
|
||||
return (_rq: express.Request, rs: express.Response) => {
|
||||
rs.json({ failed: failure, message: msg, data: data });
|
||||
return (_rq: express.Request, rs: express.Response<genericResponse>) => {
|
||||
rs.json({ failure: failure, errors: errors, message: msg, data: data });
|
||||
};
|
||||
}
|
||||
type RecNetResponse = {
|
||||
|
||||
Reference in New Issue
Block a user