Joh*_*ika 5 middleware node.js firebase google-cloud-functions
借助Firebase HTTP功能,我们可以安装express并使用中间件。中间件对于在函数执行之前检查先决条件非常有用(除其他外)。例如,我们可以在中间件中检查身份验证、授权等,这样就不需要在每个端点定义中重复它们。
开发人员如何使用Firebase 可调用函数实现同样的目标?当您有大量可调用函数时,如何提取通常位于链式中间件中的所有功能?
Joh*_*ika 13
似乎没有现成的可调用函数中间件框架,因此受此启发,我推出了自己的中间件框架。NPM 上有一些通用的链式中间件框架,但我需要的中间件非常简单,以至于构建自己的中间件比配置一个库来使用可调用函数更容易。
可选:如果您使用 TypeScript,则中间件的类型声明:
export type Middleware = (
data: any,
context: functions.https.CallableContext,
next: (
data: any,
context: functions.https.CallableContext,
) => Promise<any>,
) => Promise<any>;
Run Code Online (Sandbox Code Playgroud)
中间件框架如下:
export const withMiddlewares = (
middlewares: Middleware[],
handler: Handler,
) => (data: any, context: functions.https.CallableContext) => {
const chainMiddlewares = ([
firstMiddleware,
...restOfMiddlewares
]: Middleware[]) => {
if (firstMiddleware)
return (
data: any,
context: functions.https.CallableContext,
): Promise<any> => {
try {
return firstMiddleware(
data,
context,
chainMiddlewares(restOfMiddlewares),
);
} catch (error) {
return Promise.reject(error);
}
};
return handler;
};
return chainMiddlewares(middlewares)(data, context);
};
Run Code Online (Sandbox Code Playgroud)
要使用它,您可以附加withMiddlewares到任何可调用函数。例如:
export const myCallableFunction = functions.https.onCall(
withMiddlewares([assertAppCheck, assertAuthenticated], async (data, context) => {
// Your callable function handler
}),
);
Run Code Online (Sandbox Code Playgroud)
上面的例子中使用了2个中间件。它们被拴在一起,所以assertAppCheck首先被叫,然后是assertAuthenticated,只有当它们都通过后,你的传手才会被叫。
这两个中间件是:
断言应用检查:
/**
* Ensures request passes App Check
*/
const assertAppCheck: Middleware = (data, context, next) => {
if (context.app === undefined)
throw new HttpsError('failed-precondition', 'Failed App Check.');
return next(data, context);
};
export default assertAppCheck;
Run Code Online (Sandbox Code Playgroud)
断言已验证:
/**
* Ensures user is authenticated
*/
const assertAuthenticated: Middleware = (data, context, next) => {
if (!context.auth?.uid)
throw new HttpsError('unauthenticated', 'Unauthorized.');
return next(data, context);
};
export default assertAuthenticated;
Run Code Online (Sandbox Code Playgroud)
作为奖励,这里有一个验证中间件,它使用 Joi 确保在调用处理程序之前验证数据:
const validateData: (schema: Joi.ObjectSchema<any>) => Middleware = (
schema: Joi.ObjectSchema<any>,
) => {
return (data, context, next) => {
const validation = schema.validate(data);
if (validation.error)
throw new HttpsError(
'invalid-argument',
validation.error.message,
);
return next(data, context);
};
};
export default validateData;
Run Code Online (Sandbox Code Playgroud)
像这样使用验证中间件:
export const myCallableFunction = functions.https.onCall(
withMiddlewares(
[
assertAuthenticated,
validateData(
Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
}),
),
],
async (data, context) => {
// Your handler
},
),
);
Run Code Online (Sandbox Code Playgroud)
2024-01-05 第二代更新
这是针对函数进行调整的代码gen2:
import { CallableRequest } from 'firebase-functions/v2/https';
export type Handler<T = any, Return = any> = (
request: CallableRequest<T>,
) => Promise<Return>;
export type Middleware<T = any, Return = any> = (
request: CallableRequest<T>,
next: (request: CallableRequest<T>) => Promise<Return>,
) => Promise<Return>;
export const withMiddlewares =
<T = any, Return = any>(
middlewares: Middleware<T, Return>[],
handler: Handler<T, Return>,
) =>
(request: CallableRequest<T>): Promise<Return> => {
const chainMiddlewares = ([
firstMiddleware,
...restOfMiddlewares
]: Middleware<T, Return>[]): Handler<T, Return> => {
if (firstMiddleware)
return (request: CallableRequest<T>): Promise<Return> =>
firstMiddleware(
request,
chainMiddlewares(restOfMiddlewares),
);
else return handler;
};
return chainMiddlewares(middlewares)(request);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1611 次 |
| 最近记录: |