Jelajahi Sumber

Allow objectId coercion and fix typing for fetchEntity

Co-authored-by: Eric Mc Sween
<5454374+emcsween@users.noreply.github.com>
GitOrigin-RevId: 1953b7b1378403b6f2fce0608f78232cb39cff88
Andrew Rumble 1 tahun lalu
induk
melakukan
c5d6d60963

+ 29 - 3
services/web/app/src/Features/UserMembership/UserMembershipMiddleware.js

@@ -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: z.string(), // slug
+  }),
+})
+
+const PostgresIdEntitySchema = z.object({
+  entityName: z.literal(['institution', 'team']),
   params: z.object({
   params: z.object({
-    id: zz.objectId(),
+    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() {
 function fetchEntity() {
   return expressify(async (req, res, next) => {
   return expressify(async (req, res, next) => {
     const { params } = validateReq(req, fetchEntitySchema)
     const { params } = validateReq(req, fetchEntitySchema)

+ 5 - 0
services/web/app/src/infrastructure/Validation.js

@@ -43,6 +43,11 @@ function validate(schema) {
 const zz = {
 const zz = {
   objectId: () =>
   objectId: () =>
     z.string().refine(ObjectId.isValid, { message: 'invalid Mongo 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)),
 }
 }
 
 
 /**
 /**