Skip to content

Commit 7b6ae0e

Browse files
author
heimanba
committed
generate tablestore instance
1 parent e0c531b commit 7b6ae0e

File tree

7 files changed

+227
-156
lines changed

7 files changed

+227
-156
lines changed

dist/index.js

Lines changed: 89 additions & 89 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package-lock.json

Lines changed: 6 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@
2121
"scripts": {
2222
"start": "npm run watch",
2323
"watch": "tsc -w",
24-
"prebuild": "rimraf package-lock.json && rimraf dist && rimraf node_modules && npm i",
24+
"prebuild": "rimraf dist",
2525
"build": "npm run esbuild",
26-
"esbuild": "esbuild src/index.ts --bundle --log-level=error --minify --platform=node --format=cjs --target=node10.4 --external:@serverless-devs/core --outfile=dist/index.js"
26+
"esbuild": "esbuild src/index.ts --bundle --log-level=error --minify --platform=node --format=cjs --target=node10.4 --external:@serverless-devs/core --outfile=dist/index.js",
27+
"publish": "s cli registry publish"
2728
},
2829
"dependencies": {
2930
"@serverless-devs/core": "latest",

publish.yaml

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,13 @@ Type: Component
22
Name: cd-generate
33
Provider:
44
- 阿里云
5-
Version: 0.0.8
6-
Description: 简短的描述/介绍
7-
HomePage: 项目首页地址
5+
Version: 0.0.12
6+
Description: 服务于serverless-cd初始化组件
7+
HomePage: https://cd.serverless-devs.com
88
Tags:
99
- 部署函数
1010
- 部署组件
1111
Category: 开源项目
12-
# Service:
13-
# 服务名:
14-
# Authorities: #权限描述
15-
# - 创建函数 # 所需要的权限
1612
Commands:
1713
generate: 生成资源
1814
Properties:

src/constants.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ export const OTS_DEFAULT_CONFIG = {
1010
OTS_TOKEN_INDEX_NAME: 'token_index',
1111
};
1212

13+
export const OTS_INSTANCE_NAME = 'serverless-cd';
14+
1315
export const OTHER_DEFAULT_CONFIG = {
1416
SESSION_EXPIRATION: '5184000000',
1517
// OSS_BUCKET: 'test',

src/index.ts

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import { lodash as _, fse, inquirer } from "@serverless-devs/core";
2-
import path from 'path';
3-
import logger from './common/logger';
4-
import { IInput, IProps } from './common/entity';
5-
import * as constants from './constants';
2+
import path from "path";
3+
import logger from "./common/logger";
4+
import { IInput, IProps } from "./common/entity";
5+
import * as constants from "./constants";
66
import { getCred } from "./util";
7-
import Domain from './resource/domain';
8-
import Ots from './resource/tablestore';
7+
import Domain from "./resource/domain";
8+
import Ots from "./resource/tablestore";
99
import Oss from "./resource/oss";
1010

11-
12-
export default class ComponentDemo {
11+
export default class CdGenerate {
1312
/**
1413
* demo 实例
1514
* @param inputs
@@ -19,34 +18,37 @@ export default class ComponentDemo {
1918
logger.debug(`input: ${JSON.stringify(inputs.props)}`);
2019
const { props = {} as IProps } = inputs;
2120

22-
const configPath = _.get(inputs, 'path.configPath');
21+
const configPath = _.get(inputs, "path.configPath");
2322
const cwd = configPath ? path.dirname(configPath) : process.cwd();
2423

2524
// TODO: 如果 .env 已经存在,优先使用配置文件
26-
const envFilePath = path.join(cwd, '.env');
25+
const envFilePath = path.join(cwd, ".env");
2726
if (fse.existsSync(envFilePath)) {
2827
const answers: any = await inquirer.prompt([
2928
{
30-
type: 'list',
31-
name: 'overwrite',
29+
type: "list",
30+
name: "overwrite",
3231
message: `${envFilePath} is exised, determine whether to overwrite the file. Exit if not overwritten`,
33-
choices: ['yes', 'no'],
32+
choices: ["yes", "no"],
3433
},
3534
]);
36-
if (answers.overwrite === 'no') {
35+
if (answers.overwrite === "no") {
3736
return;
3837
}
3938
}
4039

41-
const dbPrefix = _.get(props, 'dbPrefix', 'cd');
40+
const dbPrefix = _.get(props, "dbPrefix", "cd");
4241

43-
const omitProps = _.omit(props, ['dbPrefix', 'serviceName']);
44-
const p = _.mapValues(_.defaults(omitProps, constants.OTS_DEFAULT_CONFIG), (value, key) => {
45-
if (_.has(constants.OTS_DEFAULT_CONFIG, key)) {
46-
return `${dbPrefix}_${value}`;
42+
const omitProps = _.omit(props, ["dbPrefix", "serviceName"]);
43+
const p = _.mapValues(
44+
_.defaults(omitProps, constants.OTS_DEFAULT_CONFIG),
45+
(value, key) => {
46+
if (_.has(constants.OTS_DEFAULT_CONFIG, key)) {
47+
return `${dbPrefix}_${value}`;
48+
}
49+
return value;
4750
}
48-
return value;
49-
});
51+
);
5052
logger.debug(`transform ots values: ${JSON.stringify(p)}`);
5153

5254
const credentials = await getCred(inputs);
@@ -58,44 +60,43 @@ export default class ComponentDemo {
5860
ACCESS_KEY_SECRET: credentials.AccessKeySecret,
5961
};
6062

61-
62-
logger.info('init bucket start');
63-
if (_.toLower(envConfig.OSS_BUCKET) === 'auto') {
63+
logger.info("init bucket start");
64+
if (_.toLower(envConfig.OSS_BUCKET) === "auto") {
6465
const oss = new Oss(envConfig);
6566
await oss.putBucket();
6667
envConfig.OSS_BUCKET = oss.bucketName;
6768
}
68-
logger.info('init bucket success');
69+
logger.info("init bucket success");
6970

70-
logger.info('init domain start');
71-
if (_.toLower(envConfig.DOMAIN) === 'auto') {
71+
logger.info("init domain start");
72+
if (_.toLower(envConfig.DOMAIN) === "auto") {
7273
const domain = new Domain({
7374
project: {
7475
...inputs.project,
7576
},
7677
credentials,
77-
appName: 'get-domain',
78+
appName: "get-domain",
7879
});
7980
envConfig.DOMAIN = await domain.get({
80-
type: 'fc',
81+
type: "fc",
8182
user: envConfig.ACCOUNTID,
8283
region: envConfig.REGION,
83-
service: _.get(props, 'serviceName', 'serverless-cd'),
84-
function: 'gen-domain',
84+
service: _.get(props, "serviceName", "serverless-cd"),
85+
function: "auto",
8586
});
86-
} else if (_.includes(envConfig.DOMAIN, '://')) {
87-
envConfig.DOMAIN = envConfig.DOMAIN.split('://')[1]; // 不带协议
87+
} else if (_.includes(envConfig.DOMAIN, "://")) {
88+
envConfig.DOMAIN = envConfig.DOMAIN.split("://")[1]; // 不带协议
8889
}
89-
logger.info('init domain success');
90+
logger.info("init domain success");
9091

91-
logger.info('init ots start');
92+
logger.info("init ots start");
9293
const ots = new Ots(envConfig);
9394
await ots.init();
94-
logger.info('init ots success');
95+
logger.info("init ots success");
9596

96-
let envStr = '';
97-
_.forEach(envConfig, (value, key) => envStr += `${key}=${value || ''}\n`);
98-
fse.outputFileSync(envFilePath, envStr)
97+
let envStr = "";
98+
_.forEach(envConfig, (value, key) => (envStr += `${key}=${value || ""}\n`));
99+
fse.outputFileSync(envFilePath, envStr);
99100

100101
// if (!envConfig.GITHUB_CLIENT_ID) {
101102
// logger.log('Please populate.env with GITHUB_CLIENT_ID before deploy', 'red');
@@ -105,3 +106,7 @@ export default class ComponentDemo {
105106
// }
106107
}
107108
}
109+
110+
const OtsDemo = Ots;
111+
112+
export { OtsDemo };

src/resource/tablestore/index.ts

Lines changed: 80 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
// refer: https://github.com/aliyun/aliyun-tablestore-nodejs-sdk
2-
import { Client } from 'tablestore';
3-
import { lodash as _ } from '@serverless-devs/core';
4-
import { IProps } from '../../common/entity';
5-
import * as generateDbParams from './generate-db-params';
6-
import logger from '../../common/logger';
7-
2+
import { Client } from "tablestore";
3+
import { lodash as _, popCore } from "@serverless-devs/core";
4+
import { IProps } from "../../common/entity";
5+
import * as generateDbParams from "./generate-db-params";
6+
import logger from "../../common/logger";
7+
import { OTS_INSTANCE_NAME } from "../../constants";
88

99
export default class Ots {
1010
client: Client;
11+
popClient: any;
1112
dbConfig: any;
13+
envConfig: any;
1214

1315
constructor(envConfig: IProps) {
16+
this.envConfig = envConfig;
17+
this.popClient = new popCore({
18+
accessKeyId: envConfig.ACCESS_KEY_ID,
19+
accessKeySecret: envConfig.ACCESS_KEY_SECRET,
20+
endpoint: `https://ots.${envConfig.REGION}.aliyuncs.com`,
21+
apiVersion: "2016-06-20",
22+
});
23+
1424
this.client = new Client({
1525
accessKeyId: envConfig.ACCESS_KEY_ID,
1626
accessKeySecret: envConfig.ACCESS_KEY_SECRET,
@@ -52,24 +62,70 @@ export default class Ots {
5262
];
5363
}
5464

65+
// 初始化实例
66+
async initInstance() {
67+
const popClient = this.popClient;
68+
const instanceName =
69+
this.envConfig?.OTS_INSTANCE_NAME || OTS_INSTANCE_NAME;
70+
let isExistInstance = false;
71+
logger.info(`Init Ots Instance ${instanceName} Start`);
72+
try {
73+
await popClient.request(
74+
"GetInstance",
75+
{ InstanceName: instanceName },
76+
{
77+
method: "GET",
78+
formatParams: false,
79+
}
80+
);
81+
isExistInstance = true;
82+
} catch (error) {}
83+
84+
if (isExistInstance) {
85+
logger.debug(`Ots Instance Exist ${instanceName} Exist`);
86+
logger.info(`Init Ots Instance ${instanceName} Success`);
87+
return;
88+
}
89+
logger.debug(`Create Instance ${instanceName} Start...`);
90+
await popClient.request(
91+
"InsertInstance",
92+
{ InstanceName: instanceName },
93+
{
94+
method: "POST",
95+
formatParams: false,
96+
}
97+
);
98+
logger.info(`Init Ots Instance ${instanceName} Success`);
99+
}
100+
55101
async init() {
56-
for (const { name, indexName, genTableParams, genIndexParams } of this.dbConfig) {
102+
await this.initInstance();
103+
for (const { name, indexName, genTableParams, genIndexParams } of this
104+
.dbConfig) {
57105
logger.debug(`handler ${name} start`);
58106
await this.handlerTable(name, genTableParams(name));
59107

60108
if (indexName) {
61-
await this.handlerIndex(name, indexName, genIndexParams(name, indexName));
109+
await this.handlerIndex(
110+
name,
111+
indexName,
112+
genIndexParams(name, indexName)
113+
);
62114
}
63115

64116
logger.debug(`handler ${name} end`);
65117
}
66118
}
67119

68-
private async handlerIndex(tableName: string, indexName: string, params: any) {
120+
private async handlerIndex(
121+
tableName: string,
122+
indexName: string,
123+
params: any
124+
) {
69125
logger.debug(`need handler index: ${indexName}`);
70126
try {
71127
await this.client.describeSearchIndex({ tableName, indexName });
72-
128+
73129
logger.debug(`check index ${indexName} exist, skip create`);
74130
return;
75131
} catch (ex) {
@@ -78,12 +134,17 @@ export default class Ots {
78134
throw ex;
79135
}
80136
}
81-
logger.debug(`need create index ${indexName}, params: ${JSON.stringify(params, null, 2)}`);
137+
logger.debug(
138+
`need create index ${indexName}, params: ${JSON.stringify(
139+
params,
140+
null,
141+
2
142+
)}`
143+
);
82144
await this.client.createSearchIndex(params);
83145
logger.debug(`create index ${indexName} success`);
84146
}
85147

86-
87148
private async handlerTable(tableName: string, params: any): Promise<Boolean> {
88149
logger.debug(`check table ${tableName}`);
89150
try {
@@ -96,7 +157,13 @@ export default class Ots {
96157
throw ex;
97158
}
98159
}
99-
logger.debug(`need create table ${tableName}, params: ${JSON.stringify(params, null, 2)}`);
160+
logger.debug(
161+
`need create table ${tableName}, params: ${JSON.stringify(
162+
params,
163+
null,
164+
2
165+
)}`
166+
);
100167
await this.client.createTable(params);
101168
logger.debug(`create table ${tableName} success`);
102169
}

0 commit comments

Comments
 (0)