delete the null eater

This commit is contained in:
MathMan05 2025-04-30 19:11:43 -05:00 committed by Rory&
parent af70a7f21b
commit 5488874476
2 changed files with 2 additions and 40 deletions

View File

@ -28,7 +28,6 @@ import {
ajv,
getPermission,
getRights,
normalizeBody,
} from "@spacebar/util";
import { AnyValidateFunction } from "ajv/dist/core";
import { NextFunction, Request, Response } from "express";
@ -121,7 +120,7 @@ export function route(opts: RouteOptions) {
}
if (validate) {
const valid = validate(normalizeBody(req.body));
const valid = validate(req.body);
if (!valid) {
const fields: Record<
string,

View File

@ -46,44 +46,7 @@ export const ajv = new Ajv({
addFormats(ajv);
export function validateSchema<G extends object>(schema: string, data: G): G {
const valid = ajv.validate(schema, normalizeBody(data));
const valid = ajv.validate(schema, data);
if (!valid) throw ajv.errors;
return data;
}
// Normalizer is introduced to workaround https://github.com/ajv-validator/ajv/issues/1287
// this removes null values as ajv doesn't treat them as undefined
// normalizeBody allows to handle circular structures without issues
// taken from https://github.com/serverless/serverless/blob/master/lib/classes/ConfigSchemaHandler/index.js#L30 (MIT license)
export const normalizeBody = (body: object = {}) => {
const normalizedObjectsSet = new WeakSet();
const normalizeObject = (object: object) => {
if (normalizedObjectsSet.has(object)) return;
normalizedObjectsSet.add(object);
if (Array.isArray(object)) {
for (const [, value] of object.entries()) {
if (typeof value === "object") normalizeObject(value);
}
} else {
for (const [key, value] of Object.entries(object)) {
if (value == null) {
if (
key === "icon" ||
key === "avatar" ||
key === "banner" ||
key === "splash" ||
key === "discovery_splash"
)
continue;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
delete object[key];
} else if (typeof value === "object") {
normalizeObject(value);
}
}
}
};
normalizeObject(body);
return body;
};