Skip to content

Commit

Permalink
#79 introduced express to better manage google function routes with z…
Browse files Browse the repository at this point in the history
…od validation
  • Loading branch information
fcamblor committed Mar 28, 2024
1 parent 84c77eb commit 4574a83
Show file tree
Hide file tree
Showing 6 changed files with 138 additions and 41 deletions.
65 changes: 33 additions & 32 deletions cloud/functions/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cloud/functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@types/lodash": "^4.14.194",
"axios": "^1.3.6",
"cheerio": "1.0.0-rc.12",
"express": "4.19.2",
"firebase-admin": "^11.5.0",
"firebase-functions": "4.8.1",
"lodash": "^4.17.21",
Expand Down
11 changes: 5 additions & 6 deletions cloud/functions/src/functions/http/hello.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import * as functions from "firebase-functions";
import {sendResponseMessage} from "./utils";
import {Response} from "express";

const helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello voxxrin logs!", {structuredData: true});
return sendResponseMessage(response, 200, "Hello from Voxxrin!");
});

export default helloWorld
export default async (response: Response, pathParams: {}, queryParams: {who?: string}) => {
functions.logger.info("Hello voxxrin logs!", {structuredData: true});
return sendResponseMessage(response, 200, `Hello ${queryParams.who || "nobody"} from Voxxrin!`);
};
10 changes: 10 additions & 0 deletions cloud/functions/src/functions/http/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {Routes} from "./utils";
import * as z from "zod";
import type {Express} from 'express';
import helloWorld from "./hello";

export function declareExpressHttpRoutes(app: Express) {
// For testing purposes only
Routes.get(app, `/helloWorld`, z.object({ query: z.object({ who: z.string().optional() })}), helloWorld);

}
77 changes: 77 additions & 0 deletions cloud/functions/src/functions/http/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import * as functions from "firebase-functions";
import {Response} from "firebase-functions";
import * as z from "zod";
import {RouteParameters} from "express-serve-static-core";
import * as express from "express";
import {AnyZodObject} from "zod";
import { type Express, NextFunction} from "express";

export function extractSingleQueryParam(request: functions.https.Request, paramName: string) {
const value = request.query[paramName];
Expand Down Expand Up @@ -44,3 +49,75 @@ export async function logPerf<T>(message: string, callback: () => Promise<T>) {

return results;
}

type RequestZodObject = z.ZodObject<{
query?: AnyZodObject,
path?: AnyZodObject,
}>
type RequestWithBodyZodObject = z.ZodObject<{
body?: AnyZodObject,
query?: AnyZodObject,
path?: AnyZodObject,
}>


const validateRouteWith =
(schema: z.AnyZodObject) =>
async (req: express.Request, res: express.Response, next: NextFunction) => {
try {
await schema.parseAsync({
body: req.body,
query: req.query,
path: req.params,
});
return next();
} catch (error) {
return res.status(412).json(error);
}
};

export const Routes = {
post: function<
ROUTE extends string,
VALIDATION_SCHEMA extends RequestWithBodyZodObject,
QUERY_PARAMS = z.infer<VALIDATION_SCHEMA>['query'],
BODY = z.infer<VALIDATION_SCHEMA>['body'],
PATH_PARAMS = Omit< RouteParameters<ROUTE>, keyof z.infer<VALIDATION_SCHEMA>['path']> & z.infer<VALIDATION_SCHEMA>['path']
>(app: Express, route: ROUTE, schema: VALIDATION_SCHEMA, callback: (res: express.Response, pathParams: PATH_PARAMS, queryParams: QUERY_PARAMS, body: BODY) => void) {
app.post(route, validateRouteWith(schema), (req, res) => {
callback(res, req.params as PATH_PARAMS, req.query as QUERY_PARAMS, req.body as BODY)
})
},
put: function<
ROUTE extends string,
VALIDATION_SCHEMA extends RequestWithBodyZodObject,
QUERY_PARAMS = z.infer<VALIDATION_SCHEMA>['query'],
BODY = z.infer<VALIDATION_SCHEMA>['body'],
PATH_PARAMS = Omit< RouteParameters<ROUTE>, keyof z.infer<VALIDATION_SCHEMA>['path']> & z.infer<VALIDATION_SCHEMA>['path']
>(app: Express, route: ROUTE, schema: VALIDATION_SCHEMA, callback: (res: express.Response, pathParams: PATH_PARAMS, queryParams: QUERY_PARAMS, body: BODY) => void) {
app.put(route, validateRouteWith(schema), (req, res) => {
callback(res, req.params as PATH_PARAMS, req.query as QUERY_PARAMS, req.body as BODY)
})
},
get: function<
ROUTE extends string,
VALIDATION_SCHEMA extends RequestZodObject,
QUERY_PARAMS = z.infer<VALIDATION_SCHEMA>['query'],
PATH_PARAMS = Omit< RouteParameters<ROUTE>, keyof z.infer<VALIDATION_SCHEMA>['path']> & z.infer<VALIDATION_SCHEMA>['path']
>(app: Express, route: ROUTE, schema: VALIDATION_SCHEMA, callback: (res: express.Response, pathParams: PATH_PARAMS, queryParams: QUERY_PARAMS) => void) {
app.get(route, validateRouteWith(schema), (req, res) => {
callback(res, req.params as PATH_PARAMS, req.query as QUERY_PARAMS)
})
},
delete: function<
ROUTE extends string,
VALIDATION_SCHEMA extends RequestZodObject,
QUERY_PARAMS = z.infer<VALIDATION_SCHEMA>['query'],
PATH_PARAMS = Omit< RouteParameters<ROUTE>, keyof z.infer<VALIDATION_SCHEMA>['path']> & z.infer<VALIDATION_SCHEMA>['path']
>(app: Express, route: ROUTE, schema: VALIDATION_SCHEMA, callback: (res: express.Response, pathParams: PATH_PARAMS, queryParams: QUERY_PARAMS) => void) {
app.delete(route, validateRouteWith(schema), (req, res) => {
callback(res, req.params as PATH_PARAMS, req.query as QUERY_PARAMS)
})
}
}

15 changes: 12 additions & 3 deletions cloud/functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import crawl from "./functions/http/crawl"
import hello from "./functions/http/hello"
import {migrateFirestoreSchema} from "./functions/http/migrateFirestoreSchema";
import {onUserTalksNoteCreate, onUserTalksNoteUpdate} from "./functions/firestore/onUserTalkNotes"
import {onUserCreated} from "./functions/firestore/onUserCreated";
Expand All @@ -12,9 +11,14 @@ import deprecatedEventStats from "./functions/http/event/deprecatedEventStats";
import talkFeedbacksViewers from "./functions/http/event/talkFeedbacksViewers";
import publicEventStats from "./functions/http/event/publicEventStats";
import {globalStats} from "./functions/http/event/globalStatistics";
import * as express from 'express';
import * as functions from 'firebase-functions';
import {declareExpressHttpRoutes} from "./functions/http/routes";

// For testing purposes only
exports.helloWorld = hello
const app = express()
app.use(express.json());

// Legacy HTTP Endpoints declaration... please use declareRoutes() instead !

// For organizers
exports.crawl = crawl
Expand All @@ -30,6 +34,11 @@ exports.eventStats = deprecatedEventStats
exports.migrateFirestoreSchema = migrateFirestoreSchema
exports.globalStats = globalStats

// Express handler
declareExpressHttpRoutes(app)
exports.api = functions.https.onRequest(app);

// Firebase handlers
exports.onUserTalksNoteCreate = onUserTalksNoteCreate
exports.onUserTalksNoteUpdate = onUserTalksNoteUpdate
exports.onUserCreated = onUserCreated
Expand Down

0 comments on commit 4574a83

Please sign in to comment.