1 | import { existsSync, mkdirSync } from 'fs';
|
2 | import { join, sep } from 'path';
|
3 | import { loadConfig, loadTs } from '@faasjs/load';
|
4 | import Logger from '@faasjs/logger';
|
5 | import deepMerge from '@faasjs/deep_merge';
|
6 | import { CloudFunction } from '@faasjs/cloud_function';
|
7 |
|
8 | class Deployer {
|
9 | constructor(data) {
|
10 | data.name = data.filename.replace(data.root, '').replace('.func.ts', '');
|
11 | data.version = new Date().toLocaleString('zh-CN', {
|
12 | hour12: false,
|
13 | timeZone: 'Asia/Shanghai',
|
14 | }).replace(/[^0-9]+/g, '_');
|
15 | data.logger = new Logger('Deployer');
|
16 | const Config = loadConfig(data.root, data.filename);
|
17 | if (!data.env)
|
18 | data.env = process.env.FaasEnv || Config.defaults.deploy.env;
|
19 | data.config = Config[data.env];
|
20 | if (!data.config)
|
21 | throw Error(`Config load failed: ${data.env}`);
|
22 | data.tmp = join(data.root, 'tmp', data.env, data.name, data.version) + sep;
|
23 | data.tmp.split(sep).reduce(function (acc, cur) {
|
24 | acc += sep + cur;
|
25 | if (!existsSync(acc))
|
26 | mkdirSync(acc);
|
27 | return acc;
|
28 | });
|
29 | this.deployData = data;
|
30 | }
|
31 | async deploy() {
|
32 | const data = this.deployData;
|
33 | const loadResult = await loadTs(data.filename, { tmp: true });
|
34 | const func = loadResult.module;
|
35 | if (!func)
|
36 | throw Error(`Func load failed: ${data.filename}`);
|
37 | if (func.config)
|
38 | data.config = deepMerge(data.config, func.config);
|
39 | data.dependencies = deepMerge(loadResult.dependencies, func.dependencies);
|
40 |
|
41 | const includedCloudFunction = [];
|
42 | for (let i = 0; i < func.plugins.length; i++) {
|
43 | const plugin = func.plugins[i];
|
44 | if (!plugin.type) {
|
45 | data.logger.error('Unknow plugin type: %o', plugin);
|
46 | throw Error('[Deployer] Unknow plugin type');
|
47 | }
|
48 | if (plugin.type === 'cloud_function')
|
49 | includedCloudFunction.push({
|
50 | index: i,
|
51 | plugin
|
52 | });
|
53 | }
|
54 |
|
55 | if (includedCloudFunction.length)
|
56 | for (const plugin of includedCloudFunction) {
|
57 | func.plugins.splice(plugin.index, 1);
|
58 | func.plugins.push(plugin.plugin);
|
59 | }
|
60 | else {
|
61 | const functionPlugin = new CloudFunction();
|
62 | func.plugins.push(functionPlugin);
|
63 | }
|
64 | await func.deploy(this.deployData);
|
65 | return this.deployData;
|
66 | }
|
67 | }
|
68 |
|
69 | export { Deployer };
|