db-permission.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // 参考文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/permission.html
  2. const app = getApp()
  3. const sliderWidth = 96
  4. Page({
  5. onShareAppMessage() {
  6. return {
  7. title: '权限管理',
  8. path: 'page/cloud/pages/db-permission/db-permission'
  9. }
  10. },
  11. data: {
  12. openid: '',
  13. permissions: ['仅创建者可写,所有人可读', '仅创建者可读写', '仅管理端可写,所有人可读', '仅管理端可读写'],
  14. currentPermissionIndex: 0,
  15. tabs: [
  16. ['我的个性签名', '阿白的个性签名'],
  17. ['我的邮箱', '阿绿的邮箱'],
  18. [],
  19. [],
  20. ],
  21. activeTabIndex: 0,
  22. sliderOffset: 0,
  23. sliderLeft: 0,
  24. querying: false,
  25. updating: false,
  26. hasMyWhatsUp: false,
  27. myWhatsUp: '',
  28. adminWhatsUp: '',
  29. myEmail: '',
  30. adminEmail: '',
  31. hasProduct: false,
  32. product: {},
  33. serverData: '',
  34. },
  35. onLoad() {
  36. if (app.globalData.openid) {
  37. this.setData({
  38. openid: app.globalData.openid
  39. })
  40. } else {
  41. wx.showLoading({
  42. title: '正在初始化...'
  43. })
  44. app.getUserOpenIdViaCloud()
  45. .then(openid => {
  46. this.setData({
  47. openid
  48. })
  49. wx.hideLoading()
  50. return openid
  51. }).catch(err => {
  52. console.error(err)
  53. wx.hideLoading()
  54. wx.showModal({
  55. content: '初始化失败,请检查网络',
  56. showCancel: false
  57. })
  58. })
  59. }
  60. const {
  61. myWhatsUp, adminWhatsUp, myEmail, adminEmail
  62. } = app.globalData
  63. this.setData({
  64. hasMyWhatsUp: !!myWhatsUp,
  65. myWhatsUp: myWhatsUp || '',
  66. adminWhatsUp: adminWhatsUp || '',
  67. myEmail: myEmail || '',
  68. adminEmail: adminEmail || '',
  69. })
  70. this.initTabs()
  71. },
  72. initTabs() {
  73. const currentPermissionIndex = this.data.currentPermissionIndex
  74. const tabLength = this.data.tabs[currentPermissionIndex].length
  75. const that = this
  76. wx.getSystemInfo({
  77. success(res) {
  78. that.setData({
  79. sliderLeft: (res.windowWidth / tabLength - sliderWidth) / 2,
  80. sliderOffset: res.windowWidth / tabLength * that.data.activeTabIndex
  81. })
  82. }
  83. })
  84. },
  85. onTabClick(e) {
  86. this.setData({
  87. sliderOffset: e.currentTarget.offsetLeft,
  88. activeTabIndex: Number(e.currentTarget.id)
  89. })
  90. },
  91. onPermissionChange(e) {
  92. const oldIndex = this.data.currentPermissionIndex
  93. const newIndex = Number(e.detail.value)
  94. if (oldIndex !== newIndex) {
  95. this.setData({
  96. currentPermissionIndex: Number(newIndex),
  97. activeTabIndex: 0
  98. })
  99. this.initTabs()
  100. }
  101. },
  102. bindInput(e) {
  103. const {name} = e.currentTarget.dataset
  104. this.setData({
  105. [name]: e.detail.value
  106. })
  107. },
  108. showErrorModal(name, err) {
  109. let errMsg = name + '失败'
  110. if (err.toString().indexOf('permission denied') >= 0) {
  111. errMsg += ':无权限操作'
  112. }
  113. wx.showModal({
  114. content: errMsg,
  115. showCancel: false
  116. })
  117. },
  118. // 根据 openid 获取第一条数据
  119. queryOneByOpenId(collection, openid, options = {
  120. showLoading: false,
  121. showError: false,
  122. success: null,
  123. fail: null
  124. }) {
  125. const {
  126. showLoading, showError, success: successCallback, fail: failCallback
  127. } = options
  128. if (showLoading) {
  129. this.setData({
  130. querying: true
  131. })
  132. }
  133. const db = wx.cloud.database()
  134. const _openid = openid || this.data.openid
  135. db.collection(collection).where({
  136. _openid
  137. }).get({
  138. success: res => {
  139. console.log('[数据库] [查询记录] 成功: ', res)
  140. const resFirstData = res.data[0] || {}
  141. // 返回的不是要查询用户的记录,是由于没有读权限,视为查询失败
  142. if (resFirstData._openid && resFirstData._openid !== _openid) {
  143. const err = new Error('database permission denied')
  144. if (showError) this.showErrorModal('获取', err)
  145. if (failCallback) failCallback.call(this, err)
  146. } else if (successCallback) {
  147. successCallback.call(this, res.data[0])
  148. }
  149. },
  150. fail: err => {
  151. if (showError) this.showErrorModal('获取', err)
  152. console.error('[数据库] [查询记录] 失败:', err)
  153. if (failCallback) failCallback.call(this, err)
  154. },
  155. complete: () => {
  156. if (showLoading) {
  157. this.setData({
  158. querying: false
  159. })
  160. }
  161. }
  162. })
  163. },
  164. // 根据 openid 更新数据
  165. updateOneByOpenId(collection, openid, data, options = {
  166. showLoading: false,
  167. showError: false,
  168. success: null,
  169. fail: null
  170. }) {
  171. const {
  172. showLoading, showError, success: successCallback, fail: failCallback
  173. } = options
  174. if (showLoading) {
  175. this.setData({
  176. updating: true
  177. })
  178. }
  179. const db = wx.cloud.database()
  180. // 限制每人仅存一条记录,先查询是否已存在记录
  181. this.queryOneByOpenId(collection, openid || '', {
  182. success: dbData => {
  183. if (dbData) { // 已有数据,进行更新操作
  184. db.collection(collection).doc(dbData._id).update({
  185. data,
  186. success: res => {
  187. console.log('[数据库] [更新记录] 成功: ', res)
  188. if (successCallback) successCallback.call(this, res.stats)
  189. },
  190. fail: err => {
  191. if (showError) this.showErrorModal('设置', err)
  192. console.error('[数据库] [更新记录] 失败:', err)
  193. if (failCallback) failCallback.call(this, err)
  194. },
  195. complete: () => {
  196. if (showLoading) {
  197. this.setData({
  198. updating: false
  199. })
  200. }
  201. }
  202. })
  203. } else if (!openid || openid === this.data.openid) { // 还没有插入过数据且要操作的是自己的数据,进行新增操作
  204. db.collection(collection).add({
  205. data,
  206. success: res => {
  207. console.log('[数据库] [新增记录] 成功:', res)
  208. if (successCallback) successCallback.call(this, {_id: res._id})
  209. },
  210. fail: err => {
  211. if (showError) this.showErrorModal('设置', err)
  212. console.error('[数据库] [新增记录] 失败:', err)
  213. if (failCallback) failCallback.call(this, err)
  214. },
  215. complete: () => {
  216. if (showLoading) {
  217. this.setData({
  218. updating: false
  219. })
  220. }
  221. }
  222. })
  223. } else {
  224. const err = new Error('database permission denied')
  225. if (showError) this.showErrorModal('设置', err)
  226. if (failCallback) failCallback.call(this, err)
  227. if (showLoading) {
  228. this.setData({
  229. updating: false
  230. })
  231. }
  232. }
  233. },
  234. fail: err => {
  235. if (showError) this.showErrorModal('设置', err)
  236. if (failCallback) failCallback.call(this, err)
  237. if (showLoading) {
  238. this.setData({
  239. updating: false
  240. })
  241. }
  242. }
  243. })
  244. },
  245. // perm1:仅创建者可写,所有人可读
  246. queryMyWhatsUp() {
  247. this.queryOneByOpenId('perm1', '', {
  248. showLoading: true,
  249. showError: true,
  250. success: data => {
  251. const content = (data && data.whatsUp) || ''
  252. wx.showModal({
  253. title: '获取成功',
  254. content: content ? '个性签名为:' + content : '个性签名为空',
  255. showCancel: false
  256. })
  257. }
  258. })
  259. },
  260. updateMyWhatsUp() {
  261. const data = {
  262. whatsUp: this.data.myWhatsUp
  263. }
  264. this.updateOneByOpenId('perm1', '', data, {
  265. showLoading: true,
  266. showError: true,
  267. success: () => {
  268. app.globalData.myWhatsUp = this.data.myWhatsUp
  269. this.setData({
  270. hasMyWhatsUp: true
  271. })
  272. wx.showModal({
  273. content: '设置成功',
  274. showCancel: false
  275. })
  276. }
  277. })
  278. },
  279. queryAdminWhatsUp() {
  280. this.queryOneByOpenId('perm1', 'kiki', {
  281. showLoading: true,
  282. showError: true,
  283. success: data => {
  284. const content = (data && data.whatsUp) || ''
  285. wx.showModal({
  286. title: '获取成功',
  287. content: content ? '个性签名为:' + content : '个性签名为空',
  288. showCancel: false
  289. })
  290. }
  291. })
  292. },
  293. updateAdminWhatsUp() {
  294. const data = {
  295. whatsUp: this.data.adminWhatsUp
  296. }
  297. this.updateOneByOpenId('perm1', 'kiki', data, {
  298. showLoading: true,
  299. showError: true,
  300. success: res => {
  301. if (res.updated === 0) {
  302. wx.showModal({
  303. content: '设置失败:无权限操作',
  304. showCancel: false
  305. })
  306. } else {
  307. app.globalData.adminWhatsUp = this.data.adminWhatsUp
  308. wx.showModal({
  309. content: '设置成功',
  310. showCancel: false
  311. })
  312. }
  313. }
  314. })
  315. },
  316. // perm2:仅创建者可读写
  317. queryMyEmail() {
  318. this.queryOneByOpenId('perm2', '', {
  319. showLoading: true,
  320. showError: true,
  321. success: data => {
  322. const content = (data && data.email) || ''
  323. wx.showModal({
  324. title: '获取成功',
  325. content: content ? '邮箱为:' + content : '邮箱为空',
  326. showCancel: false
  327. })
  328. }
  329. })
  330. },
  331. updateMyEmail() {
  332. const data = {
  333. email: this.data.myEmail
  334. }
  335. this.updateOneByOpenId('perm2', '', data, {
  336. showLoading: true,
  337. showError: true,
  338. success: () => {
  339. app.globalData.myEmail = this.data.myEmail
  340. wx.showModal({
  341. content: '设置成功',
  342. showCancel: false
  343. })
  344. }
  345. })
  346. },
  347. queryAdminEmail() {
  348. this.queryOneByOpenId('perm2', 'popo', {
  349. showLoading: true,
  350. showError: true,
  351. success: data => {
  352. const content = (data && data.email) || ''
  353. wx.showModal({
  354. title: '获取成功',
  355. content: content ? '邮箱为:' + content : '邮箱为空',
  356. showCancel: false
  357. })
  358. }
  359. })
  360. },
  361. updateAdminEmail() {
  362. const data = {
  363. email: this.data.adminEmail
  364. }
  365. this.updateOneByOpenId('perm2', 'popo', data, {
  366. showLoading: true,
  367. showError: true,
  368. success: () => {
  369. app.globalData.adminEmail = this.data.adminEmail
  370. wx.showModal({
  371. content: '设置成功',
  372. showCancel: false
  373. })
  374. }
  375. })
  376. },
  377. // perm3:仅管理端可写,所有人可读
  378. queryProduct() {
  379. this.queryOneByOpenId('perm3', 'admin', {
  380. showLoading: true,
  381. showError: true,
  382. success: data => {
  383. const price = (data && data.price) || null
  384. wx.showModal({
  385. title: '获取成功',
  386. content: price !== null ? '商品价格为:' + price : '商品价格暂未设置',
  387. showCancel: false
  388. })
  389. }
  390. })
  391. },
  392. updateProductPrice() {
  393. const data = {
  394. price: parseInt(this.data.product.price, 10)
  395. }
  396. this.updateOneByOpenId('perm3', 'admin', data, {
  397. showLoading: true,
  398. showError: true,
  399. success: () => {
  400. wx.showModal({
  401. content: '设置成功',
  402. showCancel: false
  403. })
  404. }
  405. })
  406. },
  407. // perm4:仅管理端可读写
  408. queryServerData() {
  409. this.queryOneByOpenId('perm4', 'server', {
  410. showLoading: true,
  411. showError: true,
  412. success: data => {
  413. const content = (data && data.serverData) || ''
  414. wx.showModal({
  415. title: '获取成功',
  416. content: content ? '后台流水数据为:' + content : '后台流水数据为空',
  417. showCancel: false
  418. })
  419. }
  420. })
  421. },
  422. updateServerData() {
  423. const data = {
  424. data: this.data.serverData
  425. }
  426. this.updateOneByOpenId('perm4', 'server', data, {
  427. showLoading: true,
  428. showError: true,
  429. success: () => {
  430. wx.showModal({
  431. content: '设置成功',
  432. showCancel: false
  433. })
  434. }
  435. })
  436. },
  437. })