Allow objectId coercion and fix typing for fetchEntity

Co-authored-by: Eric Mc Sween
<5454374+emcsween@users.noreply.github.com>
GitOrigin-RevId: 1953b7b1378403b6f2fce0608f78232cb39cff88
This commit is contained in:
Andrew Rumble
2025-09-03 10:58:15 +01:00
committed by Copybot
parent 8cfec73ba3
commit c5d6d60963
2 changed files with 34 additions and 3 deletions

View File

@@ -246,13 +246,39 @@ function fetchEntityConfig(entityName) {
}
}
// fetch the entity with id and config, and set it in the request
const fetchEntitySchema = z.object({
const SlugEntitySchema = z.object({
entityName: z.literal('publisher'),
params: z.object({
id: zz.objectId(),
id: z.string(), // slug
}),
})
const PostgresIdEntitySchema = z.object({
entityName: z.literal(['institution', 'team']),
params: z.object({
id: z.coerce.number().positive(),
}),
})
const ObjectIdEntitySchema = z.object({
entityName: z.literal([
'group',
'groupAdmin',
'groupManagers',
'groupMember',
]),
params: z.object({
id: zz.coercedObjectId(),
}),
})
const fetchEntitySchema = z.discriminatedUnion('entityName', [
SlugEntitySchema,
ObjectIdEntitySchema,
PostgresIdEntitySchema,
])
// fetch the entity with id and config, and set it in the request
function fetchEntity() {
return expressify(async (req, res, next) => {
const { params } = validateReq(req, fetchEntitySchema)

View File

@@ -43,6 +43,11 @@ function validate(schema) {
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)),
}
/**