Skip to content

Commit

Permalink
add serverless of version-control
Browse files Browse the repository at this point in the history
  • Loading branch information
wbh1328551759 committed Feb 22, 2021
1 parent 07c32ed commit 5856637
Show file tree
Hide file tree
Showing 8 changed files with 760 additions and 640 deletions.
70 changes: 70 additions & 0 deletions packages/version-control-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# 快速构建 koa-starter

**中文** | [English](./README_EN.md)

## 简介

koa-starter 模板使用 Tencent SCF 组件及其触发器能力,方便的在腾讯云创建,配置和管理一个 koa-starter 应用。

## 快速开始

### 1. 安装

```bash
# 安装 Serverless Framework
npm install -g serverless
```

### 2. 创建

通过如下命令直接下载该例子:

```bash
serverless init koa-starter --name example
cd example
```

### 3. 部署

`serverless.yml` 文件所在的项目根目录,运行以下指令,将会弹出二维码,直接扫码授权进行部署:

```bash
serverless deploy
```

> **说明**:如果鉴权失败,请参考 [权限配置](https://cloud.tencent.com/document/product/1154/43006) 进行授权。
### 4. 查看状态

执行以下命令,查看您部署的项目信息:

```bash
serverless info
```

### 5. 移除

可以通过以下命令移除 koa-starter 应用

```bash
serverless remove
```

### 账号配置(可选)

serverless 默认支持扫描二维码登录,用户扫描二维码后会自动生成一个 `.env` 文件并将密钥存入其中.
如您希望配置持久的环境变量/秘钥信息,也可以本地创建 `.env` 文件,
把从[API 密钥管理](https://console.cloud.tencent.com/cam/capi)中获取的 `SecretId``SecretKey` 填入其中.

> 如果没有腾讯云账号,可以在此[注册新账号](https://cloud.tencent.com/register)
```bash
# 腾讯云的配置信息
touch .env
```

```
# .env file
TENCENT_SECRET_ID=123
TENCENT_SECRET_KEY=123
```
80 changes: 80 additions & 0 deletions packages/version-control-api/README_EN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Quickly create and deploy koa-starter application

[中文](./README.md) | **English**

## Introduction

Easily deploy koa-starter applications to Tencent Cloud's serverless infrastructure using this Serverless Framework Component.
Your application will auto-scale, never charge you for idle time, and require little-to-zero administration.

## Quick Start

### 1. Install

```bash
# Install Serverless Framework
npm install -g serverless
```

### 2. Initialize

Initializing the koa-starter template by running this following command:

```bash
serverless init koa-starter --name example
cd example
```

### 3. Deploy

You can use following command to deploy the APP.

```bash
cd koa-starter
serverless deploy
```

This command will walk you through signing up a Tencent Cloud Account to deploy the APP.

### 4. Monitor

Anytime you need to know more about your running express instance, you can run `serverless info` to view the most critical info.
This is especially helpful when you want to know the outputs of your instances so that you can reference them in another instance.
You will also see a url where you'll be able to view more info about your instance on the Serverless Dashboard.

It also shows you the status of your instance, when it was last deployed, and how many times it was deployed.
To dig even deeper, you can pass the --debug flag to view the state of your component instance in case the deployment failed for any reason.

```bash
serverless info
```

### 5. Remove

If you wanna tear down your entire infrastructure that was created during deployment,
just run `serverless remove` and serverless will remove all the data it needs from the built-in state storage system to delete only the relevant cloud resources that it created.

```bash
serverless remove
```

### Setting up credentials (Optional)

By default, you are able to login your Tencent Cloud account by scanning QR code and an `.env` file with credentials is auto generated.
The credentials will be expired after 2 hours.
If you would like to use persistent credentials,
you can [create an API Key here](https://console.cloud.tencent.com/cam/capi) and add the `SecretId` and `SecretKey` into the `.env` file

> If you don's have a Tencent Cloud Account, you can register [here](https://cloud.tencent.com/register)
```bash
# Add your Tencent credentials here
touch .env
```


```
# .env file
TENCENT_SECRET_ID=123
TENCENT_SECRET_KEY=123
```
98 changes: 98 additions & 0 deletions packages/version-control-api/controller/version.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
'use strict';

const { Pool } = require('pg');

function ApiError(code, msg) {
const e = new Error(msg);
e.code = code;
return e;
}

let pgPool;

module.exports = {
async getPool() {
if (!pgPool) {
pgPool = new Pool({
connectionString: 'postgresql://tencentdb_8ygfbnqf:ib4%7C0)DS6%24CldO1@10.0.0.7:5432/tencentdb_8ygfbnqf\n',
});
// init table
await pgPool.query(`CREATE TABLE IF NOT EXISTS versions (
ID SERIAL PRIMARY KEY,
VERSION TEXT NOT NULL,
URL CHAR(50) NOT NULL
);`);
return pgPool;
} else {
return pgPool;
}
},
async getVersionList() {
const pool = await this.getPool();
const client = await pool.connect();
const { rows } = await client.query({
text: 'select * from versions',
});
await client.end();
return rows;
},
async addVersion(versionInfo) {
const pool = await this.getPool();
const { version, url } = versionInfo;
const deleteWhiteOfVersion = version.trim()
const deleteWhiteOfUrl = url.trim()
const existVersion = await this.getVersion(deleteWhiteOfVersion);
if (existVersion) {
throw new ApiError(1000, `Version ${deleteWhiteOfVersion} exist.`);
}
const client = await pool.connect();
const { rowCount } = await client.query({
text: 'INSERT INTO versions(version, url) VALUES($1, $2)',
values: [deleteWhiteOfVersion, deleteWhiteOfUrl],
});
await client.end();
return rowCount === 1;
},
async getVersion(version) {
try {
const pool = await this.getPool();
const client = await pool.connect();
const { rows } = await client.query({
text: 'SELECT * FROM versions WHERE version = $1',
values: [version],
});
await client.end();
if (rows.length > 0) {
return rows;
}
return false;
} catch (e) {
throw new ApiError(1001, e);
}
},
async getUrlByVersion(version){
try{
const pool = await this.getPool();
const client = await pool.connect();
const { rows } = await client.query({
text: 'SELECT URL FROM versions WHERE version = $1',
values: [version],
});
await client.end();
return rows;
}catch (e) {
throw new ApiError(1001, e);
}
},
async deleteVersion(version) {
const pool = await this.getPool();
const client = await pool.connect();
const { rows } = await client.query({
text: 'DELETE FROM versions WHERE version = $1',
values: [version],
});
await client.end();
return rows;
},
};

21 changes: 21 additions & 0 deletions packages/version-control-api/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Serverless Component - Express.js</title>
<style lang="css">
h1 {
text-align: center;
width: 600px;
margin: 300px auto;
}
</style>
</head>
<body>
<h1>
Welcome to Koa.js application created by
<a href="https://serverlesscloud.cn/">Serverless Framework.</a>
</h1>
</body>
</html>
19 changes: 19 additions & 0 deletions packages/version-control-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "koa-starter",
"version": "1.0.0",
"description": "",
"main": "sls.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "yugasun",
"license": "MIT",
"devDependencies": {
"@types/koa-router": "^7.4.1",
"koa": "^2.11.0",
"koa-bodyparser": "^4.3.0",
"koa-router": "^8.0.8",
"koa-sendfile": "^2.0.1",
"pg": "^7.14.0"
}
}
20 changes: 20 additions & 0 deletions packages/version-control-api/serverless.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
component: koa
name: dapp-version-control-api
app: dapp-version-control-db

inputs:
entryFile: sls.js #以您实际入口文件名为准
src:
src: ./
exclude:
- .env
region: ap-guangzhou
functionName: dapp-version-api # 云函数名称
runtime: Nodejs10.15
serviceName: dappVersionService # api网关服务名称
apigatewayConf:
protocols:
- http
- https
environment: release
enableCORS: true # 允许跨域
17 changes: 17 additions & 0 deletions packages/version-control-api/sls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const Koa = require('koa')
const KoaRouter = require('koa-router')
const sendFile = require('koa-sendfile')
const path = require('path')

const app = new Koa()
const router = new KoaRouter()

// Routes
router.get(`/*`, async (ctx) => {
await sendFile(ctx, path.join(__dirname, 'index.html'))
})

app.use(router.allowedMethods()).use(router.routes());

// don't forget to export!
module.exports = app
Loading

0 comments on commit 5856637

Please sign in to comment.