unicloud-db.vue 12.5 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>
fxy060608's avatar
fxy060608 已提交
15 16 17 18
import { initVueI18n } from '@dcloudio/uni-i18n'
import messages from './i18n/index'

const { t } = initVueI18n(messages)
fxy060608's avatar
fxy060608 已提交
19

d-u-a's avatar
d-u-a 已提交
20 21 22 23 24 25 26 27
const events = {
  load: 'load',
  error: 'error'
}
const pageMode = {
  add: 'add',
  replace: 'replace'
}
d-u-a's avatar
d-u-a 已提交
28

d-u-a's avatar
d-u-a 已提交
29 30 31 32 33 34 35 36
const attrs = [
  'pageCurrent',
  'pageSize',
  'collection',
  'action',
  'field',
  'getcount',
  'orderby',
37 38 39 40
  'where',
  'groupby',
  'groupField',
  'distinct'
d-u-a's avatar
d-u-a 已提交
41
]
d-u-a's avatar
d-u-a 已提交
42

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

d-u-a's avatar
d-u-a 已提交
142 143 144 145 146 147 148
    this.$watch(() => {
      var al = []
      attrs.forEach(key => {
        al.push(this[key])
      })
      return al
    }, (newValue, oldValue) => {
149
      this.paginationInternal.size = this.pageSize
d-u-a's avatar
d-u-a 已提交
150

d-u-a's avatar
d-u-a 已提交
151 152 153 154 155
      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 已提交
156
        }
d-u-a's avatar
d-u-a 已提交
157 158 159 160 161 162 163 164
      }
      if (needReset) {
        this.clear()
        this.reset()
      }
      if (newValue[0] !== oldValue[0]) {
        this.paginationInternal.current = this.pageCurrent
      }
d-u-a's avatar
d-u-a 已提交
165

d-u-a's avatar
d-u-a 已提交
166 167
      this._execLoadData()
    })
d-u-a's avatar
d-u-a 已提交
168

d-u-a's avatar
d-u-a 已提交
169 170 171 172 173 174 175
    // #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 已提交
176 177 178
          }
        }
      }
d-u-a's avatar
d-u-a 已提交
179 180 181
      window.unidev.clientDB.data.push(this._debugDataList)
    }
    // #endif
d-u-a's avatar
d-u-a 已提交
182

d-u-a's avatar
d-u-a 已提交
183 184 185 186 187 188 189
    // #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 已提交
190
      }
d-u-a's avatar
d-u-a 已提交
191 192 193 194 195 196 197 198 199 200 201
    }
    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 已提交
202
        }
d-u-a's avatar
d-u-a 已提交
203 204
        parent = parent.$parent
        maxDepth--
d-u-a's avatar
d-u-a 已提交
205
      }
d-u-a's avatar
d-u-a 已提交
206 207
    }
    // #endif
d-u-a's avatar
d-u-a 已提交
208

d-u-a's avatar
d-u-a 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221
    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 已提交
222 223
        }
      }
d-u-a's avatar
d-u-a 已提交
224 225 226 227 228 229
    }
  },
  // #endif
  methods: {
    loadData (args1, args2) {
      let callback = null
230
      let clear = false
d-u-a's avatar
d-u-a 已提交
231 232
      if (typeof args1 === 'object') {
        if (args1.clear) {
233 234 235 236 237
          if (this.pageData === pageMode.replace) {
            this.clear()
          } else {
            clear = args1.clear
          }
d-u-a's avatar
d-u-a 已提交
238
          this.reset()
d-u-a's avatar
d-u-a 已提交
239
        }
d-u-a's avatar
d-u-a 已提交
240 241
        if (args1.current !== undefined) {
          this.paginationInternal.current = args1.current
d-u-a's avatar
d-u-a 已提交
242
        }
d-u-a's avatar
d-u-a 已提交
243 244
        if (typeof args2 === 'function') {
          callback = args2
d-u-a's avatar
d-u-a 已提交
245
        }
d-u-a's avatar
d-u-a 已提交
246 247 248 249
      } else if (typeof args1 === 'function') {
        callback = args1
      }

250
      this._execLoadData(callback, clear)
d-u-a's avatar
d-u-a 已提交
251 252
    },
    loadMore () {
253
      if (this._isEnded || this.loading) {
d-u-a's avatar
d-u-a 已提交
254 255
        return
      }
256 257 258 259 260

      if (this.pageData === pageMode.add) {
        this.paginationInternal.current++
      }

d-u-a's avatar
d-u-a 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274
      this._execLoadData()
    },
    refresh () {
      this.clear()
      this._execLoadData()
    },
    clear () {
      this._isEnded = false
      this.dataList = []
    },
    reset () {
      this.paginationInternal.current = 1
    },
    add (value, {
275 276
      action,
      showToast = true,
d-u-a's avatar
d-u-a 已提交
277 278 279
      toastTitle,
      success,
      fail,
280 281 282 283
      complete,
      needConfirm = true,
      needLoading = true,
      loadingTitle = ''
d-u-a's avatar
d-u-a 已提交
284
    } = {}) {
285 286 287 288 289
      if (needLoading) {
        uni.showLoading({
          title: loadingTitle
        })
      }
d-u-a's avatar
d-u-a 已提交
290
      /* eslint-disable no-undef */
291 292 293 294 295
      let db = uniCloud.database()
      if (action) {
        db = db.action(action)
      }

d-u-a's avatar
d-u-a 已提交
296 297
      db.collection(this.collection).add(value).then((res) => {
        success && success(res)
298 299
        if (showToast) {
          uni.showToast({
fxy060608's avatar
fxy060608 已提交
300
            title: toastTitle || t('uniCloud.component.add.success')
301 302
          })
        }
d-u-a's avatar
d-u-a 已提交
303 304
      }).catch((err) => {
        fail && fail(err)
305 306 307 308 309 310
        if (needConfirm) {
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }
d-u-a's avatar
d-u-a 已提交
311
      }).finally(() => {
312 313 314
        if (needLoading) {
          uni.hideLoading()
        }
d-u-a's avatar
d-u-a 已提交
315 316 317 318 319 320 321 322 323
        complete && complete()
      })
    },
    remove (id, {
      action,
      success,
      fail,
      complete,
      confirmTitle,
324 325 326 327
      confirmContent,
      needConfirm = true,
      needLoading = true,
      loadingTitle = ''
d-u-a's avatar
d-u-a 已提交
328 329 330 331
    } = {}) {
      if (!id || !id.length) {
        return
      }
332 333 334 335
      if (!needConfirm) {
        this._execRemove(id, action, success, fail, complete, needConfirm, needLoading, loadingTitle)
        return
      }
d-u-a's avatar
d-u-a 已提交
336
      uni.showModal({
fxy060608's avatar
fxy060608 已提交
337 338
        title: confirmTitle || t('uniCloud.component.remove.showModal.title'),
        content: confirmContent || t('uniCloud.component.remove.showModal.content'),
d-u-a's avatar
d-u-a 已提交
339 340 341 342
        showCancel: true,
        success: (res) => {
          if (!res.confirm) {
            return
d-u-a's avatar
d-u-a 已提交
343
          }
344
          this._execRemove(id, action, success, fail, complete, needConfirm, needLoading, loadingTitle)
d-u-a's avatar
d-u-a 已提交
345 346 347 348
        }
      })
    },
    update (id, value, {
349 350
      action,
      showToast = true,
d-u-a's avatar
d-u-a 已提交
351 352 353
      toastTitle,
      success,
      fail,
354 355 356 357
      complete,
      needConfirm = true,
      needLoading = true,
      loadingTitle = ''
d-u-a's avatar
d-u-a 已提交
358
    } = {}) {
359 360 361 362 363
      if (needLoading) {
        uni.showLoading({
          title: loadingTitle
        })
      }
d-u-a's avatar
d-u-a 已提交
364
      /* eslint-disable no-undef */
365 366 367 368 369
      let db = uniCloud.database()
      if (action) {
        db = db.action(action)
      }

d-u-a's avatar
d-u-a 已提交
370 371
      return db.collection(this.collection).doc(id).update(value).then((res) => {
        success && success(res)
372 373
        if (showToast) {
          uni.showToast({
fxy060608's avatar
fxy060608 已提交
374
            title: toastTitle || t('uniCloud.component.update.success')
375 376
          })
        }
d-u-a's avatar
d-u-a 已提交
377 378
      }).catch((err) => {
        fail && fail(err)
379 380 381 382 383 384
        if (needConfirm) {
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }
d-u-a's avatar
d-u-a 已提交
385
      }).finally(() => {
386 387 388
        if (needLoading) {
          uni.hideLoading()
        }
d-u-a's avatar
d-u-a 已提交
389 390 391
        complete && complete()
      })
    },
392
    _execLoadData (callback, clear) {
d-u-a's avatar
d-u-a 已提交
393 394 395 396 397
      if (this.loading) {
        return
      }
      this.loading = true
      this.errorMessage = ''
d-u-a's avatar
d-u-a 已提交
398

d-u-a's avatar
d-u-a 已提交
399 400 401 402 403 404 405
      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 已提交
406
        this.hasMore = !this._isEnded
d-u-a's avatar
d-u-a 已提交
407

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

410 411 412 413 414
        if (this.getcount) {
          this.paginationInternal.count = count
        }

        callback && callback(data2, this._isEnded, this.paginationInternal)
d-u-a's avatar
d-u-a 已提交
415
        this._dispatchEvent(events.load, data2)
d-u-a's avatar
d-u-a 已提交
416

417 418 419
        if (this.getone || this.pageData === pageMode.replace) {
          this.dataList = data2
        } else {
420 421 422 423 424
          if (clear) {
            this.dataList = data2
          } else {
            this.dataList.push(...data2)
          }
d-u-a's avatar
d-u-a 已提交
425
        }
d-u-a's avatar
d-u-a 已提交
426 427 428 429

        // #ifdef H5
        if (process.env.NODE_ENV === 'development') {
          this._debugDataList.length = 0
430
          const formatData = JSON.parse(JSON.stringify(this.dataList))
431 432 433 434 435
          if (Array.isArray(this.dataList)) {
            this._debugDataList.push(...formatData)
          } else {
            this._debugDataList.push(formatData)
          }
d-u-a's avatar
d-u-a 已提交
436
        }
d-u-a's avatar
d-u-a 已提交
437 438 439 440 441 442 443 444
        // #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 已提交
445
        }
d-u-a's avatar
d-u-a 已提交
446 447 448 449 450
      })
    },
    _getExec () {
      /* eslint-disable no-undef */
      let db = uniCloud.database()
d-u-a's avatar
d-u-a 已提交
451

d-u-a's avatar
d-u-a 已提交
452 453 454
      if (this.action) {
        db = db.action(this.action)
      }
d-u-a's avatar
d-u-a 已提交
455

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

d-u-a's avatar
d-u-a 已提交
458 459 460 461 462 463
      if (!(!this.where || !Object.keys(this.where).length)) {
        db = db.where(this.where)
      }
      if (this.field) {
        db = db.field(this.field)
      }
464
      if (this.groupby) {
465
        db = db.groupBy(this.groupby)
466 467 468 469 470 471 472
      }
      if (this.groupField) {
        db = db.groupField(this.groupField)
      }
      if (this.distinct === true) {
        db = db.distinct()
      }
d-u-a's avatar
d-u-a 已提交
473 474 475
      if (this.orderby) {
        db = db.orderBy(this.orderby)
      }
d-u-a's avatar
d-u-a 已提交
476

d-u-a's avatar
d-u-a 已提交
477 478 479 480
      const {
        current,
        size
      } = this.paginationInternal
481 482 483 484
      const getOptions = {}
      if (this.getcount) {
        getOptions.getCount = this.getcount
      }
485 486 487 488
      const treeOptions = {
        limitLevel: this.limitlevel,
        startWith: this.startwith
      }
489
      if (this.gettree) {
490 491 492 493
        getOptions.getTree = treeOptions
      }
      if (this.gettreepath) {
        getOptions.getTreePath = treeOptions
494 495
      }
      db = db.skip(size * (current - 1)).limit(size).get(getOptions)
d-u-a's avatar
d-u-a 已提交
496

d-u-a's avatar
d-u-a 已提交
497 498
      return db
    },
499
    _execRemove (id, action, success, fail, complete, needConfirm, needLoading, loadingTitle) {
d-u-a's avatar
d-u-a 已提交
500 501 502
      if (!this.collection || !id) {
        return
      }
d-u-a's avatar
d-u-a 已提交
503

d-u-a's avatar
d-u-a 已提交
504 505 506 507
      const ids = Array.isArray(id) ? id : [id]
      if (!ids.length) {
        return
      }
d-u-a's avatar
d-u-a 已提交
508

509 510 511 512 513 514
      if (needLoading) {
        uni.showLoading({
          mask: true,
          title: loadingTitle
        })
      }
d-u-a's avatar
d-u-a 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

      /* 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 已提交
531
        } else {
d-u-a's avatar
d-u-a 已提交
532 533 534 535
          this.removeData(ids)
        }
      }).catch((err) => {
        fail && fail(err)
536 537 538 539 540 541
        if (needConfirm) {
          uni.showModal({
            content: err.message,
            showCancel: false
          })
        }
d-u-a's avatar
d-u-a 已提交
542
      }).finally(() => {
543 544 545
        if (needLoading) {
          uni.hideLoading()
        }
d-u-a's avatar
d-u-a 已提交
546 547 548 549 550 551 552 553 554 555 556
        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 已提交
557 558
        }
      }
d-u-a's avatar
d-u-a 已提交
559 560 561
    },
    _dispatchEvent (type, data) {
      if (this._changeDataFunction) {
562
        this._changeDataFunction(data, this._isEnded, this.paginationInternal)
d-u-a's avatar
d-u-a 已提交
563
      } else {
564
        this.$emit(type, data, this._isEnded, this.paginationInternal)
d-u-a's avatar
d-u-a 已提交
565
      }
d-u-a's avatar
d-u-a 已提交
566 567
    }
  }
d-u-a's avatar
d-u-a 已提交
568
}
d-u-a's avatar
d-u-a 已提交
569
</script>