* Add routes for relations between the current schema and another schema. * * The routes are: * * - `GET /:id/[pathname]`: Get the entities of the relation with pagination. * - `POST /:id/[pathname]`: Add entities to the relation. * - `PUT /:id/[pathname]`: Replace the entities in
(
relationQueries: TwoRelationsQueries<
typeof this.schema,
GeneratedSchema<string, RelationCreateSchema, RelationSchema>
>,
pathname = tableToPathname(relationQueries.schemas[1].table),
{ disabled, hookEvent, isPaginationOptional }: Partial<RelationRoutesConfig> = {}
)
| 238 | * @see {@link TwoRelationsQueries} for the `relationQueries` configuration. |
| 239 | */ |
| 240 | addRelationRoutes< |
| 241 | RelationCreateSchema extends Partial<SchemaLike<string> & { id: string }>, |
| 242 | RelationSchema extends SchemaLike<string> & { id: string }, |
| 243 | >( |
| 244 | relationQueries: TwoRelationsQueries< |
| 245 | typeof this.schema, |
| 246 | GeneratedSchema<string, RelationCreateSchema, RelationSchema> |
| 247 | >, |
| 248 | pathname = tableToPathname(relationQueries.schemas[1].table), |
| 249 | { disabled, hookEvent, isPaginationOptional }: Partial<RelationRoutesConfig> = {} |
| 250 | ) { |
| 251 | const relationSchema = relationQueries.schemas[1]; |
| 252 | const relationSchemaId = camelCaseSchemaId(relationSchema); |
| 253 | const columns = { |
| 254 | schemaId: camelCaseSchemaId(this.schema), |
| 255 | relationSchemaId, |
| 256 | relationSchemaIds: relationSchemaId + 's', |
| 257 | }; |
| 258 | const appendHookContext = (ctx: WithHookContext<IRouterParamContext & Context>, id: string) => { |
| 259 | if (hookEvent) { |
| 260 | ctx.appendDataHookContext(hookEvent, { |
| 261 | ...buildManagementApiContext(ctx), |
| 262 | [columns.schemaId]: id, |
| 263 | }); |
| 264 | } |
| 265 | }; |
| 266 | |
| 267 | if (!disabled?.get) { |
| 268 | this.get( |
| 269 | `/:id/${pathname}`, |
| 270 | koaPagination({ isOptional: isPaginationOptional }), |
| 271 | koaGuard({ |
| 272 | params: z.object({ id: z.string().min(1) }), |
| 273 | response: relationSchema.guard.array(), |
| 274 | status: this.#collectRouteStatuses('get', [200, 404], 'relation'), |
| 275 | }), |
| 276 | this.#assembleQualifiedMiddlewares('get', 'relation'), |
| 277 | async (ctx, next) => { |
| 278 | const { id } = ctx.guard.params; |
| 279 | |
| 280 | // Ensure that the main entry exists |
| 281 | await this.queries.findById(id); |
| 282 | |
| 283 | const [totalCount, entities] = await relationQueries.getEntities( |
| 284 | relationSchema, |
| 285 | { [columns.schemaId]: id }, |
| 286 | ctx.pagination.disabled ? undefined : ctx.pagination |
| 287 | ); |
| 288 | |
| 289 | if (!ctx.pagination.disabled) { |
| 290 | ctx.pagination.totalCount = totalCount; |
| 291 | } |
| 292 | ctx.body = entities; |
| 293 | return next(); |
| 294 | } |
| 295 | ); |
| 296 | } |
| 297 |
no test coverage detected