unicloud-db.vue 11.2 KB
Newer Older
d-u-a's avatar
d-u-a 已提交
1 2
<template>
  <view>
d-u-a's avatar
d-u-a 已提交
3 4 5 6 7
    <slot
      :options="options"
      :data="dataList"
      :pagination="paginationInternal"
      :loading="loading"
d-u-a's avatar
d-u-a 已提交
8
      :hasMore="hasMore"
d-u-a's avatar
d-u-a 已提交
9 10
      :error="errorMessage"
    />
d-u-a's avatar
d-u-a 已提交
11 12 13 14
  </view>
</template>

<script>
d-u-a's avatar
d-u-a 已提交
15 16 17 18 19 20 21 22
const events = {
  load: 'load',
  error: 'error'
}
const pageMode = {
  add: 'add',
  replace: 'replace'
}
d-u-a's avatar
d-u-a 已提交
23

d-u-a's avatar
d-u-a 已提交
24 25 26 27 28 29 30 31
const attrs = [
  'pageCurrent',
  'pageSize',
  'collection',
  'action',
  'field',
  'getcount',
  'orderby',
32 33 34 35
  'where',
  'groupby',
  'groupField',
  'distinct'
d-u-a's avatar
d-u-a 已提交
36
]
d-u-a's avatar
d-u-a 已提交
37

d-u-a's avatar
d-u-a 已提交
38 39 40 41 42 43 44
export default {
  name: 'UniClouddb',
  props: {
    options: {
      type: [Object, Array],
      default () {
        return {}
d-u-a's avatar
d-u-a 已提交
45 46
      }
    },
d-u-a's avatar
d-u-a 已提交
47 48 49
    collection: {
      type: String,
      default: ''
d-u-a's avatar
d-u-a 已提交
50
    },
d-u-a's avatar
d-u-a 已提交
51 52 53 54 55 56 57 58
    action: {
      type: String,
      default: ''
    },
    field: {
      type: String,
      default: ''
    },
59 60 61 62 63 64 65 66
    orderby: {
      type: String,
      default: ''
    },
    where: {
      type: [String, Object],
      default: ''
    },
d-u-a's avatar
d-u-a 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    pageData: {
      type: String,
      default: 'add'
    },
    pageCurrent: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 20
    },
    getcount: {
      type: [Boolean, String],
      default: false
    },
83 84 85 86 87 88 89 90
    getone: {
      type: [Boolean, String],
      default: false
    },
    gettree: {
      type: [Boolean, String],
      default: false
    },
91 92 93 94
    gettreepath: {
      type: [Boolean, String],
      default: false
    },
95
    startwith: {
d-u-a's avatar
d-u-a 已提交
96 97 98
      type: String,
      default: ''
    },
99 100 101
    limitlevel: {
      type: Number,
      default: 10
d-u-a's avatar
d-u-a 已提交
102
    },
103 104 105 106 107 108 109 110 111 112 113
    groupby: {
      type: String,
      default: ''
    },
    groupField: {
      type: String,
      default: ''
    },
    distinct: {
      type: [Boolean, String],
      default: false
114 115 116 117
    },
    manual: {
      type: Boolean,
      default: false
d-u-a's avatar
d-u-a 已提交
118 119 120 121 122
    }
  },
  data () {
    return {
      loading: false,
d-u-a's avatar
d-u-a 已提交
123
      hasMore: false,
124
      dataList: this.getone ? undefined : [],
125
      paginationInternal: {},
d-u-a's avatar
d-u-a 已提交
126 127 128 129 130
      errorMessage: ''
    }
  },
  created () {
    this._isEnded = false
131 132 133 134 135
    this.paginationInternal = {
      current: this.pageCurrent,
      size: this.pageSize,
      count: 0
    }
d-u-a's avatar
d-u-a 已提交
136

d-u-a's avatar
d-u-a 已提交
137 138 139 140 141 142 143
    this.$watch(() => {
      var al = []
      attrs.forEach(key => {
        al.push(this[key])
      })
      return al
    }, (newValue, oldValue) => {
144
      this.paginationInternal.size = this.pageSize
d-u-a's avatar
d-u-a 已提交
145

d-u-a's avatar
d-u-a 已提交
146 147 148 149 150
      let needReset = false
      for (let i = 2; i < newValue.length; i++) {
        if (newValue[i] !== oldValue[i]) {
          needReset = true
          break
d-u-a's avatar
d-u-a 已提交
151
        }
d-u-a's avatar
d-u-a 已提交
152 153 154 155 156 157 158 159
      }
      if (needReset) {
        this.clear()
        this.reset()
      }
      if (newValue[0] !== oldValue[0]) {
        this.paginationInternal.current = this.pageCurrent
      }
d-u-a's avatar
d-u-a 已提交
160

d-u-a's avatar
d-u-a 已提交
161 162
      this._execLoadData()
    })
d-u-a's avatar
d-u-a 已提交
163

d-u-a's avatar
d-u-a 已提交
164 165 166 167 168 169 170
    // #ifdef H5
    if (process.env.NODE_ENV === 'development') {
      this._debugDataList = []
      if (!window.unidev) {
        window.unidev = {
          clientDB: {
            data: []
d-u-a's avatar
d-u-a 已提交
171 172 173
          }
        }
      }
d-u-a's avatar
d-u-a 已提交
174 175 176
      window.unidev.clientDB.data.push(this._debugDataList)
    }
    // #endif
d-u-a's avatar
d-u-a 已提交
177

d-u-a's avatar
d-u-a 已提交
178 179 180 181 182 183 184
    // #ifdef MP-TOUTIAO
    let changeName
    const events = this.$scope.dataset.eventOpts
    for (var i = 0; i < events.length; i++) {
      const event = events[i]
      if (event[0].includes('^load')) {
        changeName = event[1][0][0]
d-u-a's avatar
d-u-a 已提交
185
      }
d-u-a's avatar
d-u-a 已提交
186 187 188 189 190 191 192 193 194 195 196
    }
    if (changeName) {
      let parent = this.$parent
      let maxDepth = 16
      this._changeDataFunction = null
      while (parent && maxDepth > 0) {
        const fun = parent[changeName]
        if (fun && typeof fun === 'function') {
          this._changeDataFunction = fun
          maxDepth = 0
          break
d-u-a's avatar
d-u-a 已提交
197
        }
d-u-a's avatar
d-u-a 已提交
198 199
        parent = parent.$parent
        maxDepth--
d-u-a's avatar
d-u-a 已提交
200
      }
d-u-a's avatar
d-u-a 已提交
201 202
    }
    // #endif
d-u-a's avatar
d-u-a 已提交
203

d-u-a's avatar
d-u-a 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216
    if (!this.manual) {
      this.loadData()
    }
  },
  // #ifdef H5
  beforeDestroy () {
    if (process.env.NODE_ENV === 'development' && window.unidev) {
      var cd = this._debugDataList
      var dl = window.unidev.clientDB.data
      for (var i = dl.length - 1; i >= 0; i--) {
        if (dl[i] === cd) {
          dl.splice(i, 1)
          break
d-u-a's avatar
d-u-a 已提交
217 218
        }
      }
d-u-a's avatar
d-u-a 已提交
219 220 221 222 223 224
    }
  },
  // #endif
  methods: {
    loadData (args1, args2) {
      let callback = null
225
      let clear = false
d-u-a's avatar
d-u-a 已提交
226 227
      if (typeof args1 === 'object') {
        if (args1.clear) {
228 229 230 231 232
          if (this.pageData === pageMode.replace) {
            this.clear()
          } else {
            clear = args1.clear
          }
d-u-a's avatar
d-u-a 已提交
233
          this.reset()
d-u-a's avatar
d-u-a 已提交
234
        }
d-u-a's avatar
d-u-a 已提交
235 236
        if (args1.current !== undefined) {
          this.paginationInternal.current = args1.current
d-u-a's avatar
d-u-a 已提交
237
        }
d-u-a's avatar
d-u-a 已提交
238 239
        if (typeof args2 === 'function') {
          callback = args2
d-u-a's avatar
d-u-a 已提交
240
        }
d-u-a's avatar
d-u-a 已提交
241 242 243 244
      } else if (typeof args1 === 'function') {
        callback = args1
      }

245
      this._execLoadData(callback, clear)
d-u-a's avatar
d-u-a 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    },
    loadMore () {
      if (this._isEnded) {
        return
      }
      this._execLoadData()
    },
    refresh () {
      this.clear()
      this._execLoadData()
    },
    clear () {
      this._isEnded = false
      this.dataList = []
    },
    reset () {
      this.paginationInternal.current = 1
    },
    add (value, {
265 266
      action,
      showToast = true,
d-u-a's avatar
d-u-a 已提交
267 268 269 270 271 272 273
      toastTitle,
      success,
      fail,
      complete
    } = {}) {
      uni.showLoading()
      /* eslint-disable no-undef */
274 275 276 277 278
      let db = uniCloud.database()
      if (action) {
        db = db.action(action)
      }

d-u-a's avatar
d-u-a 已提交
279 280
      db.collection(this.collection).add(value).then((res) => {
        success && success(res)
281 282 283 284 285
        if (showToast) {
          uni.showToast({
            title: toastTitle || '新增成功'
          })
        }
d-u-a's avatar
d-u-a 已提交
286 287
      }).catch((err) => {
        fail && fail(err)
d-u-a's avatar
d-u-a 已提交
288
        uni.showModal({
d-u-a's avatar
d-u-a 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
          content: err.message,
          showCancel: false
        })
      }).finally(() => {
        uni.hideLoading()
        complete && complete()
      })
    },
    remove (id, {
      action,
      success,
      fail,
      complete,
      confirmTitle,
      confirmContent
    } = {}) {
      if (!id || !id.length) {
        return
      }
      uni.showModal({
        title: confirmTitle || '提示',
        content: confirmContent || '是否删除该数据',
        showCancel: true,
        success: (res) => {
          if (!res.confirm) {
            return
d-u-a's avatar
d-u-a 已提交
315
          }
d-u-a's avatar
d-u-a 已提交
316 317 318 319 320
          this._execRemove(id, action, success, fail, complete)
        }
      })
    },
    update (id, value, {
321 322
      action,
      showToast = true,
d-u-a's avatar
d-u-a 已提交
323 324 325 326 327 328 329
      toastTitle,
      success,
      fail,
      complete
    } = {}) {
      uni.showLoading()
      /* eslint-disable no-undef */
330 331 332 333 334
      let db = uniCloud.database()
      if (action) {
        db = db.action(action)
      }

d-u-a's avatar
d-u-a 已提交
335 336
      return db.collection(this.collection).doc(id).update(value).then((res) => {
        success && success(res)
337 338 339 340 341
        if (showToast) {
          uni.showToast({
            title: toastTitle || '修改成功'
          })
        }
d-u-a's avatar
d-u-a 已提交
342 343 344 345 346
      }).catch((err) => {
        fail && fail(err)
        uni.showModal({
          content: err.message,
          showCancel: false
d-u-a's avatar
d-u-a 已提交
347
        })
d-u-a's avatar
d-u-a 已提交
348 349 350 351 352
      }).finally(() => {
        uni.hideLoading()
        complete && complete()
      })
    },
353
    _execLoadData (callback, clear) {
d-u-a's avatar
d-u-a 已提交
354 355 356 357 358
      if (this.loading) {
        return
      }
      this.loading = true
      this.errorMessage = ''
d-u-a's avatar
d-u-a 已提交
359

d-u-a's avatar
d-u-a 已提交
360 361 362 363 364 365 366
      this._getExec().then((res) => {
        this.loading = false
        const {
          data,
          count
        } = res.result
        this._isEnded = data.length < this.pageSize
d-u-a's avatar
d-u-a 已提交
367
        this.hasMore = !this._isEnded
d-u-a's avatar
d-u-a 已提交
368

d-u-a's avatar
d-u-a 已提交
369
        const data2 = this.getone ? (data.length ? data[0] : undefined) : data
370

d-u-a's avatar
d-u-a 已提交
371 372
        callback && callback(data2, this._isEnded)
        this._dispatchEvent(events.load, data2)
d-u-a's avatar
d-u-a 已提交
373

374 375 376
        if (this.getone || this.pageData === pageMode.replace) {
          this.dataList = data2
        } else {
377 378 379 380 381
          if (clear) {
            this.dataList = data2
          } else {
            this.dataList.push(...data2)
          }
d-u-a's avatar
d-u-a 已提交
382 383
          if (this.dataList.length) {
            this.paginationInternal.current++
d-u-a's avatar
d-u-a 已提交
384 385
          }
        }
d-u-a's avatar
d-u-a 已提交
386

d-u-a's avatar
d-u-a 已提交
387 388
        if (this.getcount) {
          this.paginationInternal.count = count
d-u-a's avatar
d-u-a 已提交
389
        }
d-u-a's avatar
d-u-a 已提交
390 391 392 393

        // #ifdef H5
        if (process.env.NODE_ENV === 'development') {
          this._debugDataList.length = 0
394
          const formatData = JSON.parse(JSON.stringify(this.dataList))
395 396 397 398 399
          if (Array.isArray(this.dataList)) {
            this._debugDataList.push(...formatData)
          } else {
            this._debugDataList.push(formatData)
          }
d-u-a's avatar
d-u-a 已提交
400
        }
d-u-a's avatar
d-u-a 已提交
401 402 403 404 405 406 407 408
        // #endif
      }).catch((err) => {
        this.loading = false
        this.errorMessage = err
        callback && callback()
        this.$emit(events.error, err)
        if (process.env.NODE_ENV === 'development') {
          console.error(err)
d-u-a's avatar
d-u-a 已提交
409
        }
d-u-a's avatar
d-u-a 已提交
410 411 412 413 414
      })
    },
    _getExec () {
      /* eslint-disable no-undef */
      let db = uniCloud.database()
d-u-a's avatar
d-u-a 已提交
415

d-u-a's avatar
d-u-a 已提交
416 417 418
      if (this.action) {
        db = db.action(this.action)
      }
d-u-a's avatar
d-u-a 已提交
419

d-u-a's avatar
d-u-a 已提交
420
      db = db.collection(this.collection)
d-u-a's avatar
d-u-a 已提交
421

d-u-a's avatar
d-u-a 已提交
422 423 424 425 426 427
      if (!(!this.where || !Object.keys(this.where).length)) {
        db = db.where(this.where)
      }
      if (this.field) {
        db = db.field(this.field)
      }
428
      if (this.groupby) {
429
        db = db.groupBy(this.groupby)
430 431 432 433 434 435 436
      }
      if (this.groupField) {
        db = db.groupField(this.groupField)
      }
      if (this.distinct === true) {
        db = db.distinct()
      }
d-u-a's avatar
d-u-a 已提交
437 438 439
      if (this.orderby) {
        db = db.orderBy(this.orderby)
      }
d-u-a's avatar
d-u-a 已提交
440

d-u-a's avatar
d-u-a 已提交
441 442 443 444
      const {
        current,
        size
      } = this.paginationInternal
445 446 447 448
      const getOptions = {}
      if (this.getcount) {
        getOptions.getCount = this.getcount
      }
449 450 451 452
      const treeOptions = {
        limitLevel: this.limitlevel,
        startWith: this.startwith
      }
453
      if (this.gettree) {
454 455 456 457
        getOptions.getTree = treeOptions
      }
      if (this.gettreepath) {
        getOptions.getTreePath = treeOptions
458 459
      }
      db = db.skip(size * (current - 1)).limit(size).get(getOptions)
d-u-a's avatar
d-u-a 已提交
460

d-u-a's avatar
d-u-a 已提交
461 462 463 464 465 466
      return db
    },
    _execRemove (id, action, success, fail, complete) {
      if (!this.collection || !id) {
        return
      }
d-u-a's avatar
d-u-a 已提交
467

d-u-a's avatar
d-u-a 已提交
468 469 470 471
      const ids = Array.isArray(id) ? id : [id]
      if (!ids.length) {
        return
      }
d-u-a's avatar
d-u-a 已提交
472

d-u-a's avatar
d-u-a 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
      uni.showLoading({
        mask: true
      })

      /* eslint-disable no-undef */
      const db = uniCloud.database()
      const dbCmd = db.command

      let exec = db
      if (action) {
        exec = exec.action(action)
      }

      exec.collection(this.collection).where({
        _id: dbCmd.in(ids)
      }).remove().then((res) => {
        success && success(res.result)
        if (this.pageData === pageMode.replace) {
          this.refresh()
d-u-a's avatar
d-u-a 已提交
492
        } else {
d-u-a's avatar
d-u-a 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
          this.removeData(ids)
        }
      }).catch((err) => {
        fail && fail(err)
        uni.showModal({
          content: err.message,
          showCancel: false
        })
      }).finally(() => {
        uni.hideLoading()
        complete && complete()
      })
    },
    removeData (ids) {
      const il = ids.slice(0)
      const dl = this.dataList
      for (let i = dl.length - 1; i >= 0; i--) {
        const index = il.indexOf(dl[i]._id)
        if (index >= 0) {
          dl.splice(i, 1)
          il.splice(index, 1)
d-u-a's avatar
d-u-a 已提交
514 515
        }
      }
d-u-a's avatar
d-u-a 已提交
516 517 518 519 520 521 522
    },
    _dispatchEvent (type, data) {
      if (this._changeDataFunction) {
        this._changeDataFunction(data, this._isEnded)
      } else {
        this.$emit(type, data, this._isEnded)
      }
d-u-a's avatar
d-u-a 已提交
523 524
    }
  }
d-u-a's avatar
d-u-a 已提交
525
}
d-u-a's avatar
d-u-a 已提交
526
</script>