云函数实战教程
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
// 数据表 id
const TABLE_ID = 111111
const genUniqueID = (len = 5) => {
const LENGTH = len
let number = Math.floor(Math.random() * Math.pow(10, LENGTH))
let length = number.toString().length
let tmp = (0).toFixed(LENGTH).split('.')[1]
return tmp.slice(0, LENGTH - length) + number
}
exports.main = async function setHash(event) {
let MyTableObject = new BaaS.TableObject(TABLE_ID)
while (true) {
let hash = 'c' + genUniqueID()
// 设定查询条件
let query = new BaaS.Query()
query.compare('hash', '=', hash)
// 根据指定条件查询数据
let res = await MyTableObject.setQuery(query).find()
// 如数据表已存在该 hash ,则重新生成 hash 值
if (res.data.objects.length > 0) {
continue;
}
// event.data.id 为触发该云函数的当前数据行 id
let MyRecord = MyTableObject.getWithoutData(event.data.id)
// 更新 hash 字段值
await MyRecord.set('hash', hash)
return await MyRecord.update()
}
}