Writing in the front

Develop small programs, but: no back end! No operations! There is no DBA! No domain name! No certificate! No money! No time! No energy!

No relationship, can javascript, small program • cloud development take you off!

Developers can use cloud development to develop wechat mini programs and games, without building a server, you can use cloud capabilities. Cloud development provides complete cloud support for developers, weakening the concepts of back-end and operation and maintenance. Without setting up servers, core business development can be carried out using API provided by the platform, enabling rapid launch and iteration. At the same time, this capability is mutually compatible with the cloud services already used by developers, rather than mutually exclusive.

Currently, three basic capabilities are provided:

  • Cloud function: the code running in the cloud, wechat private protocol natural authentication, developers only need to write their own business logic code
  • Database: A JSON database that can be operated on the front end of an applet or read and write in cloud functions
  • Storage: upload/download cloud files directly in front of the small program, and manage them visually in the cloud development console

Step by step

This article will teach you step by step how to use applets • Cloud Development + Omip + Comi to build a applets content presentation and distribution system that supports Markdown and code highlighting.

Preview:

1. The table

Operation path: wechat developer tools → cloud development → database → Add collection

Article collection field description:

field instructions
_id Unique DATA ID. The system automatically generates data when users write data
_openid Unique identifier of the user. The system automatically generates data when the user writes data
createTime Article creation time
md The article content
order Order of articles
title The title of the article

Obviously, this table is used to store all the articles. Then set read and write permissions on the table:

Since it may be possible for users to post later, set it to the first one.

2. Initialize the project directory

$ npm i omi-cli -g 
$ omi init-cloud my-app     
$ cd my-app          
$ npm start          
Copy the code

Here is the cloud development scaffolding that uses OMIP as a scaffold and also supports Omi MPS-Cloud to create native applets:

$ npm i omi-cli -g              
$ omi init-mps-cloud my-app    
$ cd my-app/miniprogram   
$ npm install
$ npm start               
Copy the code

3. Initialize app.js

import './app.css'
import './pages/list/index'
import { render, WeElement, define } from 'omi'

define('my-app'.class extends WeElement {

  config = {
    pages: [
      'pages/list/index'.'pages/detail/index'.'pages/import/index'].window: {
      backgroundTextStyle: 'light'.navigationBarBackgroundColor: '#fff'.navigationBarTitleText: 'Omi Cloud'.navigationBarTextStyle: 'black'
    }
  }

  install() {
    if(! wx.cloud) {console.error('Please use base library 2.2.3 or above to use cloud capabilities')}else {
      wx.cloud.init({
        traceUser: true,})this.globalData.db = wx.cloud.database({
        env: 'test-06eb2e'
      })
    }
  }

  render() {
    return (
      <page-list />
    )
  }
})

render(<my-app />, '#app')
Copy the code

The env in the wx.cloud.database code parameter can be obtained from above. Generally, two environments are created, one for user test and one for production.

  • Pages /list/index List of articles
  • Pages /detail/index
  • Pages /import/index article import page (first simply import markdown through code, no UI provided)

Import MarkDown data

import { WeElement, define } from 'omi'
import data from './test.md'

const app = getApp()

define('page-import'.class extends WeElement {

  installed() {
    wx.cloud.callFunction({
      name: 'login'.data: {},
      success: res= > {
        app.globalData.openid = res.result.openid
        app.globalData.db.collection('article').add({
          data: {
            md: data.md,
            title: 'test'.createTime: app.globalData.db.serverDate()
          },
          success: (res) = > {
            console.log(res)
          },
          fail: err= > {
            console.error('[cloud function] [login] call failed ', err)
          }
        })
      },
      fail: err= > {
        console.error('[cloud function] [login] call failed ', err) } }) } ... . })Copy the code

Three points to note:

  • throughwx.cloud.callFunctionCall the cloud function to log in and get the OpenID, and then the imported data will be automatically submitted with the OpenID.
  • throughapp.globalData.db.serverDate()Obtain the server time, but the client time is unreliable
  • Article import is the responsibility of the administrator only

Note that import data from ‘./test.md’ is implemented by modifying the scripts logic in omIP.

Here’s how import Markdown works:

let code = fs.readFileSync(item).toString()
if (path.extname(item) === '.md') {
  code = `export default { md: \`${code.replace(/`/g.'\ \ `').replace(/\$/g.'\ \ $')}` \ `}
}
Copy the code

Detect a file with an MD suffix, escape the markdown string in the file from the keyword and turn it into a JS module.

This is one of the advantages of using intermediate compilation. If the native applet cannot import markdown files, of course the native applet API and surrounding ecosystem are constantly evolving. The MPS framework developed by Tencent Omi team allows you to use JSX and LESS in native applet.

The detailed code above can be viewed here.

List of pp.

Request list data

 // Display loading first
 wx.showLoading({
    title: 'Loading'
  })
  // Call the cloud function to get openID
  wx.cloud.callFunction({
    name: 'login'.data: {},
    success: res= > {
      app.globalData.openid = res.result.openid
      app.globalData.db.collection('article').field({
        title: true._id: true.order: true
      }).get().then(res= > {
        this.data.list = res.data.sort(function (a, b) {
          return a.order - b.order
        })
        this.update()
        wx.hideLoading()
      })
    },
    fail: err= > {
      console.error('[cloud function] [login] call failed ', err)
    }
  })
Copy the code
  • Request list and filter fields through field method. After all, list does not need MD field, which can reduce data transmission and save bandwidth
  • Sort the list by the order field (so that the administrator can manually reorder the list without having to issue a version)

Complete code:

import { WeElement, define } from 'omi'
import './index.css'
import arrowPng from './arrow.png'

// Get the application instance
const app = getApp()

define('page-about'.class extends WeElement {
  config = {
    navigationBarBackgroundColor: '#24292e'.navigationBarTextStyle: 'white'.navigationBarTitleText: 'Omi'.backgroundColor: '#ccc'.backgroundTextStyle: 'light'
  }

  data = {
    list: []
  }

  installed() {
    wx.showLoading({
      title: 'Loading'
    })
    wx.cloud.callFunction({
      name: 'login'.data: {},
      success: res= > {
        console.log('[login] user openID: ', res.result.openid)
        app.globalData.openid = res.result.openid
        app.globalData.db.collection('article').field({
          title: true._id: true.order: true
        }).get().then(res= > {
          this.data.list = res.data.sort(function (a, b) {
            return a.order - b.order
          })
          this.update()
          wx.hideLoading()
        })
      },
      fail: err= > {
        console.error('[cloud function] [login] call failed ', err)

      }
    })
  }

  gotoDetail = (evt) = > {
    wx.navigateTo({
      url: '.. /detail/index? id=' + evt.currentTarget.dataset.id
    })
  }

  render() {
    return (
      <view class='ctn'>
        {list.map(item => (
          <view class='item' data-id={item._id} bindtap={this.gotoDetail}>
            <text>{item.title}</text>
            <image src={arrowPng}></image>
          </view>
        ))}
      </view>)}})Copy the code

Omip lets you write WXML structures directly using JSX. The compiled WXML looks like this:

<block>
  <view class="ctn">
    <view class="item" data-id="{{item._id}}" bindtap="gotoDetail" wx:for="{{list}}" wx:for-item="item"><text>{{item.title}}</text>
      <image src="{{arrowPng}}"></image>
    </view>
  </view>
</block>
Copy the code

To note here, click on each jump details. Also be sure to use evt currentTarget. Dataset. Id, rather than using evt. Target. The dataset. Id. If you click on a text or image, you won’t get an ID.

Article Details

Comi is used here for Markdown rendering! Comi Reading, similar to The Chinese art meter, is a small program code highlighting and Markdown rendering component developed by Tencent’s Omi team. Comi is a secondary development based on the following excellent community components.

  • wxParse
  • remarkable
  • html2json
  • htmlparser
  • prism

Effect preview:

import { WeElement, define } from 'omi'
import './index.css'
import comi from '.. /.. /components/comi/comi'

// Get the application instance
const app = getApp()

define('page-about'.class extends WeElement {
  config = {
    navigationBarBackgroundColor: '#24292e'.navigationBarTextStyle: 'white'.navigationBarTitleText: ' '.backgroundColor: '#eeeeee'.backgroundTextStyle: 'light'
  }

  install(options) {
    wx.showLoading({
      title: 'Loading'
    })
    app.globalData.db.collection('article').doc(options.id).get().then(res= >{
      comi(res.data.md, this.$scope)
      wx.hideLoading()
    }).catch(err= > {
      console.error(err)
    })
  }


  render() {
    return (
      <view>
        <include src=".. /.. /components/comi/comi.wxml" />
      </view>)}})Copy the code

In addition to being used in OMIP, native applets can also use Comi:

Copy this directory to your project first.

js:

const comi = require('.. /.. /comi/comi.js');

Page({
  onLoad: function () {
    comi('You have to render md! `.this)}})Copy the code

wxml:

<include src=".. /.. /comi/comi.wxml" />
Copy the code

wxss:

@import ".. /.. /comi/comi.wxss";
Copy the code

You’re done. Keep it simple!

Cloud functions and debugging

Cloud functions are functions that run in the cloud (server side). In terms of physical design, a cloud function can be composed of multiple files, occupying a certain amount of CPU memory and other computing resources. Each cloud function is completely independent; Can be deployed in different areas. Developers do not need to buy or build a server, but only need to write function code and deploy it to the cloud to be called in the small program side, and at the same time, cloud functions can also call each other.

A cloud function is written just like a locally defined JavaScript method, and the code runs in the cloud node.js. When the cloud function is called by the applets, the defined code is executed in the Node.js runtime environment. We can perform network requests and other operations in cloud functions just like using JavaScript in node. js environment, and we can also use a variety of services through cloud function back-end SDK, such as database and storage API provided in cloud function SDK for database and storage operations. Refer to the database and storage backend API documentation for this section.

The unique advantage of cloud function of cloud development lies in its seamless integration with wechat login authentication. When the small program side calls the cloud function, the openID of the user on the small program side will be injected into the input parameters of the cloud function. The developer does not need to verify the correctness of OpenID because wechat has completed this part of authentication, so the developer can directly use the OpenID.

In this article’s mini-program, there is a todo example in which remove uses the cloud function to clear all completed tasks.

const cloud = require('wx-server-sdk')
cloud.init()

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  try {
    return await db.collection('todo').where({
      done: true
    }).remove()
  } catch (e) {
    console.error(e)
  }
}
Copy the code

However, the latest IED, cloud functions support local debugging function, interested can click here to learn about.

A link to the

  • This article source address
  • This article Comi address
  • The official tutorial
  • Applets API documentation
  • Server API documentation