index.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import * as config from '../config.local'
  2. import { create } from 'domain'
  3. export async function safeCreateCollection(db, name) {
  4. return db.createCollection(name)
  5. }
  6. export async function timer(time: number) {
  7. return new Promise(resolve => {
  8. setTimeout(() => {
  9. resolve()
  10. }, time)
  11. })
  12. }
  13. export async function safeCollection(db, name) {
  14. const collection = db.collection(name)
  15. let num = -1
  16. // 检查collection是否存在
  17. try {
  18. const res = await collection.where({}).get()
  19. // collection存在 且有数据 则删除当前collection中所有doc
  20. if (res.data.length) {
  21. await collection
  22. .where({
  23. _id: /.*/
  24. })
  25. .remove()
  26. }
  27. } catch (e) {
  28. if (e.code === 'DATABASE_COLLECTION_NOT_EXIST') {
  29. // 不存在
  30. await db.createCollection(name)
  31. }
  32. }
  33. return {
  34. async create(data) {
  35. // await db.createCollection(name)
  36. const datas = Array.isArray(data) ? data : [data]
  37. num = datas.length
  38. let result
  39. try {
  40. result = await collection.add(datas)
  41. } catch (e) {
  42. // throw e
  43. }
  44. // const getRes = await collection.doc(result.id).get()
  45. if (result.ids.length !== num) {
  46. throw Error('出现插入数据失败情况了!!')
  47. }
  48. return true
  49. },
  50. async remove() {
  51. // 加重试机制
  52. let flag = false
  53. let retryTimes = 0
  54. let result = null
  55. while (flag !== true && retryTimes++ < 4) {
  56. result = await collection
  57. .where({
  58. _id: /.*/
  59. })
  60. .remove()
  61. flag = result.deleted >= 0
  62. if (!flag) {
  63. await timer(1200) // 等1.2s
  64. }
  65. }
  66. return flag
  67. }
  68. }
  69. }
  70. // module.exports = {
  71. // safeCreateCollection,
  72. // safeCollection
  73. // }