, firebase-functions-test node-mocks-http.
FunctionCaller.js:
'use strict';
var httpMocks = require('node-mocks-http');
var eventEmitter = require('events').EventEmitter;
const FunctionCaller = class {
constructor(aYourFunctionsIndex) {
this.functions_index = aYourFunctionsIndex;
}
async postFunction(aFunctionName,aBody,aHeaders,aCookies) {
let url = (aFunctionName[0]=='/') ? aFunctionName : '/${aFunctionName}';
let options = {
method: 'POST',
url: url,
body: aBody
};
if (aHeaders)
options.headers = aHeaders;
if (aCookies) {
options.cookies = {};
for (let k in aCookies) {
let v = aCookies[k];
if (typeof(v)=='string') {
options.cookies[k] = {value: v};
} else if (typeof(v)=='object') {
options.cookies[k] = v;
}
}
}
var request = httpMocks.createRequest(options);
var response = httpMocks.createResponse({eventEmitter: eventEmitter});
var me = this;
await new Promise(function(resolve){
response.on('end', resolve);
if (me.functions_index[aFunctionName])
me.functions_index[aFunctionName](request, response);
else
me.functions_index.app(request, response);
});
return response;
}
async postObject(aFunctionName,aBody,aHeaders,aCookies) {
let response = await this.postFunction(aFunctionName,aBody,aHeaders,aCookies);
return JSON.parse(response._getData());
}
async getFunction(aFunctionName,aParams,aHeaders,aCookies) {
let url = (aFunctionName[0]=='/') ? aFunctionName : '/${aFunctionName}';
let options = {
method: 'GET',
url: url,
query: aParams
};
if (aHeaders)
options.headers = aHeaders;
if (aCookies) {
options.cookies = {};
for (let k in aCookies) {
let v = aCookies[k];
if (typeof(v)=='string') {
options.cookies[k] = {value: v};
} else if (typeof(v)=='object') {
options.cookies[k] = v;
}
}
}
var request = httpMocks.createRequest(options);
var response = httpMocks.createResponse({eventEmitter: eventEmitter});
var me = this;
await new Promise(function(resolve){
response.on('end', resolve);
if (me.functions_index[aFunctionName])
me.functions_index[aFunctionName](request, response);
else
me.functions_index.app(request, response);
});
return response;
}
async getObject(aFunctionName,aParams,aHeaders,aCookies) {
let response = await this.getFunction(aFunctionName,aParams,aHeaders,aCookies);
return JSON.parse(response._getData());
}
};
module.exports = FunctionCaller;
:
exports.app = functions.https.onRequest(expressApp);
firebase.json :
"rewrites": [
:
:
:
{
"source": "/path/to/function", "function": "app"
}
]
:
const FunctionCaller = require('../FunctionCaller');
let fire_functions = require('../index');
const fnCaller = new FunctionCaller(fire_functions);
:
let response = await fnCaller.postFunction('/path/to/function',anObject);
anObject request.body .
8 Firebase, / ..