-
Notifications
You must be signed in to change notification settings - Fork 0
/
genres.ts
74 lines (64 loc) · 2.33 KB
/
genres.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { pascalCase } from 'change-case';
import * as dynamoose from 'dynamoose';
import { Schema } from 'dynamoose/dist/Schema';
import { TableOptionsOptional } from 'dynamoose/dist/Table';
import * as fs from 'fs';
import * as glob from 'glob-promise';
import * as yaml from 'js-yaml';
import * as path from 'path';
const args = process.argv.slice(2);
const matchPattern = args[1];
const outputFile = args[2];
const deletionPolicy = 'Delete';
const globalOptions: TableOptionsOptional = {
throughput: 'ON_DEMAND',
prefix: '${self:service}-${self:provider.stage}-',
suffix: '-table',
};
async function main() {
if (!matchPattern || !outputFile) {
console.log('missing required arguments.');
return;
}
const slsResources: { Resources: Record<string, any> } = { Resources: {} };
// find all the files that match the given pattern
const files = await glob.promise(matchPattern);
await Promise.all(
files.map(async (file) => {
console.log('detected:', file);
// use the filename without extention as tablename
const fileNameExt = file.split(/[\\\/]/).pop()!;
const fileName = fileNameExt.split('.').shift()!;
const tableName = pascalCase(fileName);
// dynamic import the typescript file
const exports = await import(`.${path.sep}${file}`);
// get the first export
const schema = Object.values(exports).shift() as Schema;
// make sure it is a Schema class
if (schema.constructor.name === 'Schema') {
const model = dynamoose.model(fileName, schema, globalOptions);
// append to the resources object
slsResources.Resources[`${tableName}Table`] = {
Type: 'AWS::DynamoDB::Table',
DeletionPolicy: deletionPolicy,
Properties: await model.table().create({ return: 'request' }),
};
}
}),
);
// convert from js object to yaml
const yamlReources = yaml.dump(slsResources);
const outputPath = outputFile.split(/[\\\/]/);
// create the missing folders if necessary
if (outputPath.length > 1) {
await fs.promises.mkdir(
outputPath.slice(0, outputPath.length - 1).join(path.sep),
{ recursive: true },
);
}
// write to output file
await fs.promises.writeFile(outputFile, yamlReources);
console.log(`Serverless resources file generated at ${outputFile}`);
process.exit(0);
}
main();