Applet cloud development: rookie can do the whole stack of products

I would like to implement a full-stack product independent Why is it so hard

Daily life, we will use a lot of software products. When using these products, we see something called "front-end interface" as an input box, a button, all invisible things happen after clicking the button called "back-end services." The corresponding creator referred to as "front-end programmer", "back-end programmer", however, a complete product development is not just only the front and rear, as well as designers, architects, operation and maintenance. Is it possible that all these things have a person doing it? There may, in fact, today there are a lot of "full stack engineer", they wear many hats, it is versatile. Able to complete all aspects of a product. This of course is amazing people, they usually have many years of experience, covered a wide range, is a veteran, also a master, when there is a product idea, they can use their comprehensive expertise, enjoy the play to realize their ideas. So, in a sense, "is also a full stack freedom", you are free to implement your ideas, this is simply fantastic!

However, many times when we have a product idea, we often find, we finished the front, the back end how do? How database do? Domain name how do? The domain but also for the record? Application deployment how do? I buy what kind of server ah? CDN static resources how do? File upload server how do? Users can access the event more than a shore it? And so on ...... a lot of problems, leading to one of your idea, are short-lived in the mind, never been able to achieve them, or that your passion to achieve a full part of what they do best, when it comes time to other problems on the stop. So the sky and shouts: I wanted to do a complete independent product Why is it so hard? Young people, do not blame it all you ......

Breaking: a small cloud development program

Why use a small program to develop cloud breaking up?

Why come to breaking up with "applet cloud development"? First of all, our aim is to achieve a full-stack products. Full stack can have a variety of technical solutions, You can use any skills you will be able to achieve the purpose of the whole stack. You can develop Android, IOS, or PC station, however small program is the most practical! Why? Why do things on the phone to use the PC version? OK, since mobile version is better, it can no longer be simpler? Energy, is a small program that does not require the development of IOS, Android versions. Fast output, rapid trial and error.

Secondly, said before, the whole stack to achieve a product is not easy, for many people, even giant hard! Select the applet is already a more cost effective solution. The re-integration of cloud development, there will be a full-stack immediately. That is why the choice "applet cloud development" to breaking.

What small cloud development is the program?

What small cloud development is the program? The official document says so: developers can use cloud development program to develop micro-channel small, small games, without having to set up the server, you can use cloud capabilities. Cloud development to provide complete for developers of native cloud support and micro-channel service support, weakening the back-end maintenance concept and operation, without the need to build a server, API using the platform provided by the core business development, we can achieve rapid on-line and iteration , and this capability , with the cloud service developers already use compatible with each other, they are not mutually exclusive.

After reading the above description, you may still not very clearly know what is "small cloud development program", it does not matter, you just need to pay attention to the bold part, probably know that it "no need to set up server" from the traditional concept, this seems "three Views destroy" ye may not be the server ah? Yes, you can not have a server in the traditional sense, this model is serveless of.

So, a small cloud development program which offers something to breaking it? Let us look at the following table:

ability effect Explanation
Cloud function You do not need self-built server Code running in the cloud, natural micro-channel proprietary authentication protocol, developers only need to write their business logic code
database You do not need self-built database A tip operating either applet, can be read in the cloud database function JSON
storage You do not need self storage and CDN In the small front-end program directly upload / download files cloud, cloud development in Visual Management Console
Clouds call Native integrated micro-channel service The ability to cloud-free authentication function using a small program based on open interfaces, including server calls, the ability to get open data

The table above mentioned in some capacity "cloud development" in: "Cloud function", "database", "storage", "cloud call", we can apply these words into the application you've ever worked on, to see them which represent part. For programmers, if in doubt, nothing is a helloword not be resolved.

Combat: Retail independently developed a simple applet

Shiver more, than actual combat. Here we have to use a small cloud development program to achieve a simple retail applet.

Project ideas

Since it is a small retail program, then we can think about the general program of small retail business processes, as well as a rough sort out its function points. Now according to their own ideas about painting roughly sketch, if not inspiration can look at how other APP is designed.

According to my own thoughts after the design is this:

Functional modules: Home, Product List page, shopping cart, order confirmation, individual centers, individual orders, you tube module (an item, add classification) where goods need to upload pictures.

After combing complete function, we have to achieve something to have a preliminary concept. Next, we probably need to draw about page design, function and circulation. Initial design may not have much experience, it does not matter, began to do on the line, doing his will more and more ideas, then optimized getting better and better. . I am also the subject of much modification adjustment, finally found some ideas. My (poor) design is as follows, if not clear picture can copy the picture to see the link opens in a new window:

Description, according to the above picture is finished (I really developed a small cloud and on-line program used) shots, but I was redesign the actual time it was finally fixed after several modifications like this.

At the same time, a side note, here the front page using vant-weapp controls, very easy to use. recommend! If you're like me it is a pure back-end programmers, recommended vant-weapp as ui, very convenient. Otherwise, write your own page style, then it might not make come. Full stack is not so good dry ah. They can choose their own control, to achieve the ultimate function is a qualified full-stack.

Creating an applet cloud development projects

We first micro-channel download applet development tool, download address here after installed, the new project, the interface is as follows, APPID you need to register a. Note Then, select "applet cloud development", as shown below:

Once you've created a project directory as follows, look at where indicated 1:

If you have had experience in the development of small programs, then miniprogramunder the folder structure you must be familiar with, miniprogramthe following subdirectories are small components of the corresponding program, pictures, pages, styles, and app.js, app.json, sitemap.jsonin which componentsthe following vant-weappis mentioned above the ui component.

最后一个比较重要的文件夹就是cloudfunctions,这个目录是用来存放“云函数的”,云函数就是我们的后端。每一个云函数提供一个服务。一个个的云函数组成了我们整体的后端服务。云函数可以看做是 FaaS(function as a service)。途中,2 标记的位置的“云开发”按钮,我们点进去,就可以看到“云开发的控制台”,如下图所示:

如果上图看不清楚,可以复制链接到新的浏览器窗口查看,如图,小程序云开发默认的免费套餐有一定的额度可供使用。首页便是使用统计。然后我们能看到,有“数据库”,“存储”,“云函数”。

这里的“数据库”其实就是类似于一个 MongoDB,你可以点进去创建一个个的 collection(即:关系型数据库中的table);这里的“存储”其实就是“文件夹”,我们可以通过微信提供的 api把图片上传到“存储”中;这里的“云函数”就是我们需要实现的后端业务逻辑,他就是一个个的函数(函数由我们自己写好后上传)。一般开发过程中我们在开发者工具中的cloudfunctions目录下创建云函数(比方说是:user-add)开发完成之后在云函数目录点击右键——上传即可。然后就可以在小程序的代码中调用这个user-add云函数。

云开发之——3 分钟实现文件上传

注意:在开始云开发之前,我们现在 小程序代码的 app.js 中加入wx.cloud.init,如下:

App({
  onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明:
        //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境(第一个创建的环境)
        env: 'your-env-id',
        traceUser: true,
      })
    }
    this.globalData = {}
  }
})

上面的图中,我们已经看到了“商品添加”页面的效果,它需要我们输入商品名称、价格、并上传图片,然后保存。传统架构中,上传图片需要前端页面摆一个控件,然后后端提供一个 api用来接收前端传来的文件,通常来说这个后端 api 接收到图片之后,会将图片文件保存到自己的文件服务器或者是阿里云存储、或者是七牛云存储之类的。然后返回给你一个文件链接地址。非常麻烦,然而,小程序云开发上传文件超级简单,上代码:

页面代码:
<van-notice-bar
  scrollable="false"
  text="发布商品"
/>
  <van-field
    value="{{ productName }}"
    required
    clearable
    label="商品名称"
    placeholder="请输入商品名称"
    bind:change="inputName"
  />
    <van-field
    value="{{ productPrice }}"
    required
    clearable
    label="价格"
    icon="question-o"
     bind:click-icon="onClickPhoneIcon"
    placeholder="请输入价格"
    error-message="{{phoneerr}}"
    border="{{ false }}"
    bind:change="inputPrice"
  />

<van-action-sheet
  required
  show="{{ showSelect }}"
  actions="{{ actions }}"
  close-on-click-overlay="true"
  bind:close="toggleSelect"
  bind:select="onSelect" cancel-text="取消"
/>
  <van-field
    value="{{ productCategory }}"
    center
    readonly
    label="商品分类"
    border="{{ false }}"
    use-button-slot
  >
    <van-button slot="button" size="small" plain type="primary"  
     bind:click="toggleSelect">选择分类</van-button>
  </van-field>
  
  <van-button class="rightside" type="default" bind:click="uploadImage" >上传商品图片</van-button>
  <view class="imagePreview">
    <image src="{{productImg}}" />
  </view>
 <van-submit-bar
  price="{{ totalShow }}"
  button-text="提交"
  bind:submit="onSubmit"
  tip="{{ false }}"
 >
 </van-submit-bar> 
<van-toast id="van-toast" />
<van-dialog id="van-dialog" />

这里有个控件,绑定了uploadImage方法,其代码为:

  uploadImage:function(){
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '上传中...',
        })
        const tempFilePath = res.tempFilePaths[0]
        const name = Math.random() * 1000000;
        const cloudPath = name + tempFilePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath:cloudPath,//云存储图片名字
          filePath: tempFilePath,//临时路径
          success: res => {
            let fileID = res.fileID;
            that.setData({
              productImg: res.fileID,
            });
            wx.showToast({
              title: '图片上传成功',
            })
          },
          fail: e =>{
            wx.showToast({
              title: '上传失败',
            })
          },
          complete:()=>{
            wx.hideLoading();
          }
        });
      }
    })
  }

这里,wx.chooseImage用于调起手机选择图片(相册/相机拍照),然后wx.cloud.uploadFile用于上传图片到上面说到的云开发能力之一的“存储”中。上传图片成功之后返回一个文件 ID,类似:

cloud://release-0kj63.7265-release-0kj63-1300431985/100477.13363146288.jpg  

这个链接可以直接在小程序页面展示:

<image src="cloud://release-0kj63.7265-release-0kj63-1300431985/100477.13363146288.jpg  " />

也可以通过微信 api,装换成 http 形式的图片链接。

云开发之——操作数据库,1 分钟写完保存商品到数据库的代码

上面我们实现了商品图片上传,但是,商品图片并没有保存到数据库。正常录入商品的时候,我们会填好商品名称,价格等,然后上传图片,最终点击“保存”按钮,将商品保存到数据库。传统模式下,前端仍然是需要调用一个后端接口,通过 post 提交数据,最终由后端服务(比如 java 服务)将数据保存到数据库。小程序云开发使得操作数据库十分简单,首先我们在云开发控制台创建“商品表”,即一个 collection,取名为:products。然后我们就可以保存数据到数据库了,代码如下:

onSubmit:function(){
    // 校验代码,略
    let product = {};
    product.imgId = this.data.productImg;
    product.name= this.data.productName;
    product.categoryId = this.data.productCategoryId;
    product.price = this.data.productPrice;
    // 其他赋值,略
    const db = wx.cloud.database();
    db.collection('products').add({
     data: product,
     success(res) {
       wx.showToast({
         title: '保存成功',
       })
     }
   });
  }

以上就实现了数据入库,就这点代码,超简单,1 分钟写完,诚不欺我。其中这里的products就是我们的“商品表”,之前说过,类似 MongoDB 数据库,这里操作的是db.collection,这和 MongoDB 的语法差不多。

云开发之——使用云函数完成后端业务逻辑,订单创建

小程序云开发提供了几大能力:“数据库”,“存储”,“云函数”,前两项我们已经有所体会了。下面我们能创建一个云函数来实现订单创建。这里说明,云函数其实就是 一段JavaScript 代码,上传至云服务器之后,最终也是运行在 nodejs 环境的,只是这一切,我们不需要关心。我们只需要关心我们这个云函数提供的功能是什么就可以了。

创建云函数很简单,直接在开发工具中右键“新建Node.js 云函数”。然后以创建订单为例,假设我们创建一个云函数名为c-order-add,创建好了之后,目录是这样:

云函数的主要代码在 index.js 中,其完整代码是这样:

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: 'release-xxx'// your-env-id
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  console.log("云函数 c-order-add : ")  
  // 这里是一些逻辑处理...
  
  return await db.collection('uorder').add({
    data: {
      openid: event.userInfo.openId,
      address: event.address,
      userName: event.userName,
      phone: event.phone,
      shoppingInfo: event.shoppingInfo,
      totlePrice: event.totlePrice,
      shoppingStr: event.shoppingStr,
      remark:event.remark,
      createTime: now,
      // ...
    }
  });
}

这个云函数写好之后,需要上传到服务器,直接在云函数目录点击右键,然后点击“上传并部署”即可,这就相当于部署好了后端服务。前端小程序页面调用的写法是这样的:

let orderData={};
orderData.userName = this.data.userName;
orderData.phone = this.data.phone;
orderData.address = this.data.address;
// ....
wx.cloud.callFunction({
      // 云函数名称
      name: 'c-order-add',
      // 传给云函数的参数
      data: orderData,
      complete: res => {
        Dialog.alert({
          title: '提交成功',
          message: '您的订单成功,即将配送,请保持手机通畅。'
        }).then(() => {
          // ....
          wx.redirectTo({
            url: '../uorder/uorder'
          });
        });
      }
})

这里,向程序前端,通过wx.cloud.callFunction完成了对云函数的调用,也可以理解为对后端服务的调用。至此我们我们介绍完了,小程序云开发的功能。虽然,我只贴出了少量的代码,即保存商品,和提交订单。由于时间和篇幅有限,我不可能把整个完整的程序代码贴出来。但是你可以参照这个用法示例,将剩下的业务逻辑补充完整,最终完成“项目构思”一节中展示的成品截图效果。

小程序审核的一点经验

我开发的小程序审核在提交审核的时候遭遇了两次退回,第一次是因为:“小程序具备电商性质,个人小程序号不支持”。所以,我只好申请了一个企业小程序号,使用的是超市的营业执照。服务类目的选择也被打回了一次,最后选择了食品还提交了食品经营许可证。第二次打回是因为:“用户体验问题”。其实就是“授权索取”的问题,微信不让打开首页就“要求授权”,同时不能强制用户接受授权,得提供拒绝授权也能使用部分功能。

上面两条解决之后,更新新了好几版,都没有出现过被拒的情况。并且,有次我是夜晚 10 左右提价的审核,结果10 点多就提示审核通过,当时没看具体时间,就是接盆水泡了个脚的时间审核通过了。所以,我推断小程序审核初次审核会比较严,之后如果改动不大应该直接机审就过了。

总结及对比

这里我们可以对小程序云开发和传统模式做一个对比:

对比条目 传统模式 云开发
是否需要后端服务 需要 (如一个java应用部署在 Tomcat 中) 不需要 只需要“云函数”
是否需要域名 需要 (还得在微信后台的把域名加入安全域名) 不需要
是否需要购买服务器 需要 (你得部署后端 Java 应用,还得安装数据库) 不需要
开通云开发之后免费套餐够用
不够的话购买套餐按调用量计费
是否需要懂运维 需要
(你得会折腾服务器,数据库之类的
还得配置好相关的用户,端口,启动服务)
不需要
图片上传及 CDN 麻烦 简单
获取微信 openID 麻烦 超级简单,云函数中直接获取
···

就对比这么多吧,总之,我非常喜欢小程序云开发,小程序真的可以让你轻松干全栈。或者咱们别动不动就提“全栈”,姑且说,小程序云开发可以让你更简单、更快速、更便宜的实现你的产品落地。我自己开发的云小程序上线之后,使用了一两个月,没出现任何问题。我也不用操心服务器什么的。所以,我已经给身边很多人安利了小程序云开发了。这里我就不贴出我的小程序码了,因为已经正式给我同学的超市使用了,所以不方便让别人去产生测试数据。如果你感兴趣想看的话,可以联系我。

Guess you like

Origin www.cnblogs.com/demingblog/p/11914354.html