About the Serverless

Serverless Computing, also known as function-as-A-Service (FaaS), is a model of cloud computing. Based on platform as a Service (PaaS), serverless computing provides a micro architecture where end customers do not need to deploy, configure, or manage server services. The server services needed to run the code are provided by the cloud platform.

In the narrow sense, full stack engineering is mainly divided into three aspects: front end, back end and database. But this is undoubtedly not enough for a complete project, which also includes data management, server operation and maintenance, security and other content. So these learning costs for front-end engineers are undoubtedly very huge. So in the technology system gradually developed today, whether there is a tool to help us to achieve such a purpose?

Then there’s Serverless. Serverless can be regarded as a black box provided by cloud service platform. Developers only need to concentrate on the research and development of core business, which greatly reduces the cost of the project. We can put the front-end page and back-end content into Serverless application as a cloud function and database, and only need to write the code of business part. That is, the front-end + back-end + database part, and Serverless does the rest.

At present, there are three mature Serverless solutions: Tencent Cloud, Ali Cloud and Amazon Cloud. Under the selection, I choose Serverless Framework of Tencent Cloud to build the project.

1. Download relevant content

  • Node download, version > 10, and NPM
Node -v v12.19.0 $NPM -v 7.0.10Copy the code
  • Install Serverless globally
NPM install -g serverless serverless -v // Check the serverless version and ensure that the installation is successfulCopy the code

With the installation complete, you are ready to deploy your project!

Ii. Introduction to the basic structure of the project

  • As a full stack project, it mainly includes front-end, back-end and database, so the basic structure of the project should include:

  • The API folder is the content of cloud functions, the DB folder corresponds to the database, which needs to write the configuration of serverless cloud database, and the front folder is the front-end code.

3. Basic configuration of Serverless

React is chosen as the front-end development language, Koa as the back-end language, and PostgreSQL as the database.

  1. The first step is to add the serverless.yml file to the root of the project
App: fullstack-demo-1 // Project nameCopy the code
  1. In the API directory, create the serverless.yml file
Component: koa name: fullstack-demo-1-API app: fullstack-demo-1-DB inputs: entryFile: sls.js Env region: ap-guangzhou functionName: fullstack-demo-1-api runtime: Nodejs10.15 serviceName: ApigatewayConf: protocols: -HTTP-https environment: release enableCORS: trueCopy the code

For more configurations, see github.com/serverless-…

At the same time, create the project entry file sls.js in the API directory and install the dependencies

const Koa = require('koa')
const app = new Koa()

module.exports = app;
Copy the code
  1. Add serverless. Yml to the DB directory
Component: postgresQL #(mandatory) Reference component name, currently used postgresQL component name: fullstack-demo-1-db app: Fullstack-demo-1-db # (Optional) This SQL application name is stage: dev # (optional) : dev inputs: region: Guangzhou # Optional ap-Guangzhou, ap-Shanghai, ap-Beijing zone Ap-guangzhou -2, ap-shanghai-2, ap-Beijing -3 dBInstanceName: serverlessDB vpcConfig: vpcId: vpc-xxx subnetId: subnet-xxx extranetAccess: falseCopy the code

Note: vpcId and subnetId in vpcConfig need to be created in Tencent cloud

Search for “private Network” in Tencent cloud product and click “New”

Copy the generated vpcID, then click enter, click below the subnet, get subnetID, and copy to the db serverless. Yml corresponding location

  1. Create a controller folder in the API directory and create a user.js file that contains statements related to database operations
'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 :// XXX format,}); // init table await pgPool.query(`CREATE TABLE IF NOT EXISTS users ( ID serial NOT NULL, NAME TEXT NOT NULL, EMAIL CHAR(50) NOT NULL, SITE CHAR(50) NOT NULL ); `); return pgPool; } else { return pgPool; } }, async getUserList() { const pool = await this.getPool(); const client = await pool.connect(); const { rows } = await client.query({ text: 'select * from users', }); await client.end(); return rows; }, async createUser(user) { const pool = await this.getPool(); const { name, email, site } = user; const existUser = await this.getUserByName(name); if (existUser) { throw new ApiError(1000, `Name ${name} exist.`); } const client = await pool.connect(); const { rowCount } = await client.query({ text: 'INSERT INTO users(name, email, site) VALUES($1, $2, $3)', values: [name, email, site], }); await client.end(); return rowCount === 1; }, async getUserByName(name) { try { const pool = await this.getPool(); const client = await pool.connect(); const { rows } = await client.query({ text: 'SELECT * FROM users WHERE name = $1', values: [name], }); await client.end(); if (rows.length > 0) { return rows; } return false; } catch (e) { throw new ApiError(1001, e); } }, async deleteUserByName(name) { const pool = await this.getPool(); const client = await pool.connect(); const { rows } = await client.query({ text: 'DELETE FROM users WHERE name = $1', values: [name], }); await client.end(); return rows; }};Copy the code
  1. Create serverless. Yml in the front folder (create-react-app).
component: website
name: fullstack-demo-1-front
app: fullstack-demo-1-front

inputs:
  region: ap-guangzhou
  bucketName: fullstack-demo-1-front
  protocol: https
  src:
    src: ./
    hook: yarn run build
    dist: ./build
    envPath: ./
    index: index.html
    error: index.html
Copy the code
  1. After completing these basic configurations, run them in the root directorysls deploy, you need to scan the TWO-DIMENSIONAL code on the console for authorization.

Fourth, the generation situation

  • You will see a Website module and a KOA module generated in the Serverless Console interface

  • At this point, you can open website application, click the generated access address, you can open your own front-end page!
  • At the same time, open the console and you can see that THE JS and CSS files that need to be loaded in website application are configured with CDN acceleration

5. Database connection

  1. In the user.js file, modifyconnectionStringField issls deployField returned by the console at deployment time.
  2. At this point, after sls.js is written and deployed, it will be found that the database cannot be connected. There are two solutions
  • On the details page of the database, enable the external IPv4 address and replace the 10.0.0.xx:5432 obtained in step 1
  • To open the deployed KOA application, click Open Cloud Functions -> Function Configuration -> Edit -> Enable private networks, select the configured VPC and subnet -> Save
  1. At this point, you can call the relevant functions provided in user.js from sls.js

Six, summarized

For now, Serverless is not popular enough to take off. There are not enough documentation and examples on the web yet, so you have to test yourself when you encounter problems. But as such a versatile and powerful cloud service tool, the trend of the future, I think, is very likely to develop in this direction. Further expand the field designed by the front-end development engineer, so that the back-end can develop the deeper level of the algorithm level content. Believe that with Serverless, the front-end engineer to develop into a full stack engineer, is no longer so difficult!