Skip to content

Commit

Permalink
BO40 - Create a shared schema and validation for API (#226)
Browse files Browse the repository at this point in the history
* BO40 - Create a shared schema and validation for API

Co-authored-by: Camillo Bucciarelli <[email protected]>
  • Loading branch information
camillobucciarelli and Camillo Bucciarelli authored May 2, 2024
1 parent dde200c commit 827fecb
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
5 changes: 5 additions & 0 deletions functions/src/api/http/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createServer } from "http";
import { functionsRegion } from "../../config";
import { decodeIdToken, isOrganizer } from "../../services/auth";
import { FunctionFastifyInstance } from "./fastify-config";
import { sharedSchemas } from "./shared/shared.schema";

let requestHandler: FastifyServerFactoryHandler;

Expand Down Expand Up @@ -53,6 +54,10 @@ app
done(null, payload.body);
});

for (const schema of sharedSchemas) {
app.addSchema(schema);
}

export default onRequest({ region: functionsRegion }, (req, res) => {
app.ready((err) => {
if (err) throw err;
Expand Down
27 changes: 27 additions & 0 deletions functions/src/api/http/shared/shared.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { z } from "zod";
import { buildJsonSchemas } from "fastify-zod";

const idParamSchema = z.object({
id: z.string(),
});

const genericResponse = z.object({
message: z.string(),
});

const errorResponse = z.object({
statusCode: z.number(),
code: z.string().optional(),
error: z.string(),
message: z.string(),
});

export const { schemas: sharedSchemas, $ref: $sharedSchemaRef } =
buildJsonSchemas(
{
idParamSchema,
genericResponse,
errorResponse,
},
{ $id: "SharedSchema" },
);
16 changes: 16 additions & 0 deletions functions/src/api/http/shared/shared.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
type IdPathParam = {
id: string;
};

type GenericResponse = {
message: string;
};

type ErrorResponse = {
statusCode: number;
code?: string;
error: string;
message: string;
};

export { IdPathParam, GenericResponse, ErrorResponse };

0 comments on commit 827fecb

Please sign in to comment.