delete the null eater
This commit is contained in:
parent
af70a7f21b
commit
5488874476
@ -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,
|
||||
|
@ -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;
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user