preface

Serverless, if you do a baidu search, you will find a lot of articles about concepts and principles for Serverless, such as no operation, FaaS(function as service), BaaS(back end as service), etc. I think these articles are all well written, but after reading these articles. I just want to say that I get it, so what am I supposed to do? Here I will from the micro channel small program as a breakthrough point, to let us really to a serverless development

I think serverless

After the emergence of wechat small program, we found that we can develop front-end applications can also be placed in others. After our small program development, as long as to the developer platform point upload to complete the front-end deployment, we have to do is to deploy back-end services.

However, back-end service operation and maintenance is a very troublesome thing, can we be lazy and deploy this back-end service to others, of course, there are, that is Ali Cloud, Tencent cloud. All we need to do is deploy our locally debugged backend service

But can we be a little bit lazy, don’t deploy, and just develop the front end and back end applications on someone else’s site, just follow their rules and just upload both. Based on this idea, cloud development serverless cloud integration emerged.

In fact, this idea greatly lowers the barrier of entry for front-end developers into back-end development, which is very similar to the so-called full stack engineers among front-end developers.

Serverless in the applet

We can easily set up a Serverless application in wechat applet, as long as we choose applet cloud development when creating a new project, as shown in the picture below

In this way, in addition to our normal small program directory, there will be another cloudfunctions directory in the newly built project. As the name implies, it is the cloudfunctions directory. The so-called cloudfunctions can be understood as the interfaces called in our front-end development, that is, background service processing functions

Once we have this directory, we need to create an application. To deploy this directory, it is easy to click the fourth icon in the upper left corner of wechat development tool, Cloud Development

Once you’ve done this, right click on the CloudFunctions directory, select the environment you created, and then open the app.js file to configure your app ID.

At this point your Serverless application is set up. Check out your backend services in the Cloud Development Console tools: logging, database, and file storage are all available

The rest is to follow the rules of wechat small program to develop, the project itself has its own example.

After the function is developed, right-click the corresponding function folder under CloudFunctions. For example, the login function provided by the example here is the login folder. Select Upload and this function will become a cloudfunction, which can be seen in the cloudfunction list of the cloud development console, and then can be passed in the front-end code

wx.cloud.callFunction({
      name: 'login'.data: {},
      success: res= > {
        console.log('[login] user openID: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '.. /userConsole/userConsole',}}),fail: err= > {
        console.error('[cloud function] [login] call failed ', err)
        wx.navigateTo({
          url: '.. /deployFunctions/deployFunctions',})}})Copy the code

To call the cloud function in this way, see the official instance in the project.

Call file system, database and so on have corresponding API, you can check wechat official documents

Now it becomes clearer to look back at the concept of FaaS and BaaS, where all services are invoked through functions and all the back ends are services

Serverless at other ends

The serverless side of the small program is mentioned above. What about the other side, such as the Web side and the APP side? As far as I am concerned, Dcloud is still a mature cloud development serverless cloud integration solution of other domestic terminals. It has cooperated with Ali Cloud and Tencent Cloud, and provides uni-App multi-terminal package solution

You can build serverless cloud projects according to its official tutorial. You have to use the development tool HBuilderX provided by it. The project catalog created is almost the same as that created by wechat mini program

Then create the application and right-click CloudFunctions to select your application

Do the above steps, let’s use it to develop a simple registration page

1. Create a database table

Right-click on the CloudFunctions folder in the editor and select “Open uniCloud Web Console”. In the console, click “Cloud Databases” and create a new table named userData

2. Establish cloud functions

Right click on the CloudFunctions folder in the editor and select “New cloudfunction” and name it login. It will automatically generate index.js

'use strict';
const db = uniCloud.database() // Connect to the database
exports.main = async (event, context) => {
  const collection = db.collection('userData') // Get the userData table from the database
  const res = await collection.add(event) // Accept user data from client
  if(res){// State returns
	  return {
		  status:'sucess'}}else {
	  return {
		  status:'fail'}}};Copy the code

Then right click on the Login directory, select Upload Deployment and see the console prompt below the editor

3. Create a sign-up page

Uniapp is based on VUE so modify the page/index.vue file code as follows

<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<view class="title">{{title}}</view>
			<input type="text" v-model="username" placeholder="Username" />
			<input type="text" v-model="password" placeholder="Password" password />
			<button @click='onButtonClick'>registered</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Registration Page'.username:' '.password:' '}},onLoad(){},methods: {
			async onButtonClick(){
				const { username,password } = this
				const res = await uniCloud.callFunction({
					name:"login".data:{
						username,
						password
					}
				})
				console.log(res)
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	input{
		display: block;
		border-bottom: 1px solid #f4f4f4;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
Copy the code

This is a simple registration page with the onButtonClick method, which calls the cloud function login via unicloud. callFunction, passing in the username and password

4. The debugging

Click preview in the editor to get a page

Fill in the information point to register, then go to the cloud database in the uniCloud Web console and add a message to the table

This is the simplest registration function.

PS: In fact, such common functions as registration/login have been integrated in Dcloud, so we can directly implement them according to the API provided by the official documents

conclusion

Through cloud development serverless cloud integration, we can like the above very simple implementation of business functions, no longer need to consider how to configure this service, how to configure that service, for developers is really very convenient. And it provides a shortcut for front-end developers to switch to the full stack

I haven’t found any documentation on DCloud for service calls like Redis, message queues, etc. I don’t know if there will ever be one