@goldstack/utils-aws-lambda
Version:
Utilities for deploying AWS Lambda functions
100 lines • 3.42 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readLambdaConfig = readLambdaConfig;
const fs_1 = __importDefault(require("fs"));
const path_1 = require("path");
const LambdaConfig_1 = require("../types/LambdaConfig");
function readLambdaConfig(dir) {
const result = readLambdaConfigImpl(dir, dir);
if (!result.children) {
throw new Error(`Invalid directory ${dir}`);
}
return flattenConfig(result.children).filter((e) => e.type === LambdaConfig_1.RouteType.FUNCTION);
}
function flattenConfig(config) {
const arr = [];
for (const child of Object.entries(config)) {
const newVal = { ...child[1] };
newVal.children = undefined;
arr.push(newVal);
if (child[1].children) {
arr.push(...flattenConfig(child[1].children));
}
}
return arr;
}
function posixPath(pathString) {
return pathString.split(path_1.sep).join(path_1.posix.sep);
}
function removeExtension(path) {
return path.replace(/\.[^/.]+$/, '');
}
function makePath(configRoot, dir) {
const path = removeExtension(posixPath((0, path_1.relative)(configRoot, dir)));
if (path === '$index') {
return '/';
}
if (path.indexOf('$index') !== -1) {
let newPath = path.replace('$index', '');
// API Gateway does not accept routes like /my_route/
newPath = newPath.slice(0, newPath.length - 1);
return `/${newPath}`;
}
if (path === '$default') {
return '$default';
}
return `/${path}`;
}
function makeRoute(configRoot, dir) {
const route = makePath(configRoot, dir);
if (route === '$default') {
return '$default';
}
return `ANY ${route}`;
}
function readLambdaConfigImpl(configRoot, dir) {
const root = dir;
const rootRoute = makeRoute(configRoot, dir);
const configItem = {
name: root,
type: LambdaConfig_1.RouteType.DIR,
absoluteFilePath: dir,
path: makePath(configRoot, dir),
relativeFilePath: (0, path_1.relative)(configRoot, dir),
route: rootRoute,
};
const dirHandle = fs_1.default.opendirSync(dir);
let dirEntry;
while ((dirEntry = dirHandle.readSync()) !== null) {
if (!configItem.children) {
configItem.children = {};
}
const name = dirEntry.name;
const fullPath = (0, path_1.resolve)(root, name);
if (dirEntry.isDirectory()) {
configItem.children[name] = readLambdaConfigImpl(configRoot, fullPath);
}
else if (dirEntry.isFile()) {
if (!(dirEntry.name.endsWith('.ts') || dirEntry.name.endsWith('.tsx'))) {
continue;
}
const route = makeRoute(configRoot, fullPath);
configItem.children[name] = {
name: removeExtension(name),
type: LambdaConfig_1.RouteType.FUNCTION,
path: makePath(configRoot, fullPath),
absoluteFilePath: fullPath,
relativeFilePath: (0, path_1.relative)(configRoot, fullPath),
route: route,
};
}
else {
}
}
dirHandle.closeSync();
return configItem;
}
//# sourceMappingURL=collectLambdasFromFiles.js.map