@aimee-blue/ab-service-kit
Version:
Aimee Blue Service Template
72 lines (56 loc) • 2.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.apiOf = apiOf;
exports.callFn = exports.fetchFn = exports.defaultApiParams = exports.CLOUD_FUNCTION_ROOT_ENDPOINT = void 0;
var _nodeFetch = _interopRequireDefault(require("node-fetch"));
var _abShared = require("@aimee-blue/ab-shared");
var _env = require("../env");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const CLOUD_FUNCTION_ROOT_ENDPOINT = 'CLOUD_FUNCTION_ROOT_ENDPOINT';
exports.CLOUD_FUNCTION_ROOT_ENDPOINT = CLOUD_FUNCTION_ROOT_ENDPOINT;
const constructEndpointUri = (rootEndpoint, functionName) => rootEndpoint + functionName;
const defaultApiParams = () => ({
rootEndpoint: (0, _env.envVar)(CLOUD_FUNCTION_ROOT_ENDPOINT)
});
exports.defaultApiParams = defaultApiParams;
const fetchFn = (functionName, init, params = defaultApiParams()) => {
return (0, _nodeFetch.default)(constructEndpointUri(params.rootEndpoint, functionName), init);
};
/**
* Call function using Firebase HTTP call conventions
* @param functionName Name of the function
* @param authToken Authentication token
* @param rootEndpoint Functions root endpoint
*/
exports.fetchFn = fetchFn;
const callFn = (functionName, params = defaultApiParams()) => (data, opts = {}) => fetchFn(functionName, {
method: 'post',
body: JSON.stringify({
data
}),
headers: {
'Content-Type': 'application/json',
'cache-control': 'no-cache',
...(opts.authToken && {
Authorization: 'Bearer ' + opts.authToken
})
},
redirect: 'error'
}, params).then(async res => {
if (res.ok) {
return res.json();
}
const message = await _abShared.Errors.errorMessageFromFetchResponse(res);
throw new Error(message);
}).then(wrapped => 'result' in wrapped && wrapped.result ? wrapped.result : wrapped);
exports.callFn = callFn;
function apiOf(params = defaultApiParams()) {
return {
callFn: (name, param, opts = {}) => {
return callFn(name, params)(param, opts);
}
};
}
//# sourceMappingURL=index.js.map