uniapp(uncloud) 使用生态开发接口详情5(云公共模块)

1.uniCloud官网 云对象中云公共模块: 网站:

https://uniapp.dcloud.net.cn/uniCloud/cf-common.html

javascript 复制代码
// 官网介绍
cloudfunctions
  ├─common // 云函数公用模块目录
  |  └─hello-common // 云函数公用模块
  |     ├─package.json
  |     └─index.js // 公用模块代码,可以不使用index.js,修改 package.json 内的 main 字段可以指定此文件名
  └─use-common // 使用公用模块的云函数
     ├─package.json // 在 use-common 目录执行 npm init -y 生成
     └─index.js // 云函数入口文件
  1. 在 common 新建 demo 公共模块
javascript 复制代码
// demo => index.js
function getMessage(str) {
	let msg = {
		"success": "查询成功",
		"noSuccess": "查询失败",
		"requried": "缺少参数"
	}
	return msg[str]
}

function getCode(code) {
	let codeObj = {
		200: 200, // "查询成功",
		404: 404 // 找不到路径
	}
	return codeObj[code]
}

function usrReslut(code, msg, data, total) {
	return {
		errCode: getCode(code),
		errMsg: getMessage(msg),
		data: data,
		total: total
	}
}
module.exports = {
	getMessage,
	getCode,
	usrReslut
}
  1. 点击demo 目录, 上传公共模块
  2. 使用公共模块
javascript 复制代码
const db = uniCloud.database()
// 1. 引入
const {
	getMessage,
	getCode,
	usrReslut
} = require("demo")

module.exports = {
	_before: function() { // 通用预处理器
		const body = this.getHttpInfo().body
		if (!body) {
			throw new usrReslut(400, "requried")
		}
		this.params = JSON.parse(this.getHttpInfo().body)
		this.startTime = Date.now()
	},

	async get() {
		let {
			num
		} = this.params
		if (num == null) throw new usrReslut(400, "requried")

		const res = await db.collection("sy_product_nav").limit(num).get()
		// let result = {
		// 	errCode: getCode(0),
		// 	errMsg: getMessage("noSuccess"),
		// 	data: res.data
		// }
		// return result
		// 使用之后,保存文件,再上传部署
		return  usrReslut(200, "success", res.data, 0)
	},

	_after(error, result) {
		if (error) {
			throw error
		}
		result.timeCode = Date.now() - this.startTime

		return result
	}

}
  1. 在postman中, 使用之前的接口请求, 结果返回ok, 最后是根据自己的需求制定接口
相关推荐
浩星29 分钟前
vue3+uniapp中使用高德地图实现撒点效果
前端·vue.js·uni-app
qq_4244091916 小时前
uniapp生成的app,关于跟其他设备通信的支持和限制
uni-app
Bruce_Liuxiaowei1 天前
HarmonyOS NEXT~鸿蒙系统与Uniapp跨平台开发实践指南
华为·uni-app·harmonyos
lqj_本人1 天前
鸿蒙OS&UniApp实现的倒计时功能与倒计时组件(鸿蒙系统适配版)#三方框架 #Uniapp
华为·uni-app·harmonyos
tryCbest1 天前
uniapp如何设置uni.request可变请求ip地址
网络协议·tcp/ip·uni-app
老李不敲代码1 天前
榕壹云上门家政系统:基于Spring Boot+MySQL+UniApp的全能解决方案
spring boot·mysql·微信小程序·小程序·uni-app
锦画凉1 天前
uniapp运行到微信开发者工具报错“更改appid失败touristappidError:tourist appid”
uni-app
机构师1 天前
<uniapp><vuex><状态管理>在uniapp中,如何使用vuex实现数据共享与传递?
uni-app·vue·vuex·数据管理
好好的哦1 天前
uni-app项目从0-1基础架构搭建全流程
uni-app
冷子夜1 天前
uniapp 小程序 CSS 实现多行文本展开收起 组件
css·小程序·uni-app