mirror of
https://github.com/yu-i-i/overleaf-cep.git
synced 2026-05-23 17:19:37 +02:00
Use validation-tools library in web
GitOrigin-RevId: e10a22f5ad2efe45e12158471ffcc64c79e54125
This commit is contained in:
@@ -3,12 +3,12 @@
|
||||
const { Joi: CelebrateJoi, celebrate, errors } = require('celebrate')
|
||||
const { ObjectId } = require('mongodb-legacy')
|
||||
const { NotFoundError } = require('../Features/Errors/Errors')
|
||||
const { z } = require('zod')
|
||||
|
||||
/**
|
||||
* @import { ZodType } from 'zod'
|
||||
* @import { Request } from 'express'
|
||||
*/
|
||||
const {
|
||||
validateReq,
|
||||
z,
|
||||
zz,
|
||||
ParamsError,
|
||||
} = require('@overleaf/validation-tools')
|
||||
|
||||
const objectIdValidator = {
|
||||
type: 'objectId',
|
||||
@@ -40,35 +40,23 @@ function validate(schema) {
|
||||
return celebrate(schema, { allowUnknown: true })
|
||||
}
|
||||
|
||||
const zz = {
|
||||
objectId: () =>
|
||||
z.string().refine(ObjectId.isValid, { message: 'invalid Mongo ObjectId' }),
|
||||
coercedObjectId: () =>
|
||||
z
|
||||
.string()
|
||||
.refine(ObjectId.isValid, { message: 'invalid Mongo ObjectId' })
|
||||
.transform(val => new ObjectId(val)),
|
||||
hex: () => z.string().regex(/^[0-9a-f]*$/),
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a request against a zod schema
|
||||
*
|
||||
* @template T
|
||||
* @param {Request} req
|
||||
* @param {ZodType<T>} schema
|
||||
* @return {T}
|
||||
*/
|
||||
function validateReq(req, schema) {
|
||||
const parsed = schema.safeParse(req)
|
||||
if (parsed.success) {
|
||||
return parsed.data
|
||||
} else if (parsed.error.issues.some(issue => issue.path[0] === 'params')) {
|
||||
// Parts of the URL path failed to validate; throw a 404 rather than a 400
|
||||
throw new NotFoundError('Not found').withCause(parsed.error)
|
||||
} else {
|
||||
throw parsed.error
|
||||
const validateReqWeb = (req, schema) => {
|
||||
try {
|
||||
return validateReq(req, schema)
|
||||
} catch (err) {
|
||||
if (err instanceof ParamsError) {
|
||||
// convert into a NotFoundError that web understands
|
||||
throw new NotFoundError('Not found').withCause(err)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Joi, validate, errorMiddleware, validateReq, z, zz }
|
||||
module.exports = {
|
||||
Joi,
|
||||
validate,
|
||||
errorMiddleware,
|
||||
validateReq: validateReqWeb,
|
||||
z,
|
||||
zz,
|
||||
}
|
||||
|
||||
@@ -94,6 +94,7 @@
|
||||
"@overleaf/redis-wrapper": "*",
|
||||
"@overleaf/settings": "*",
|
||||
"@overleaf/stream-utils": "*",
|
||||
"@overleaf/validation-tools": "*",
|
||||
"@phosphor-icons/react": "^2.1.7",
|
||||
"@slack/webhook": "^7.0.2",
|
||||
"@stripe/react-stripe-js": "^3.9.0",
|
||||
|
||||
Reference in New Issue
Block a user