Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | 18x 2093x 2096x 18x 48x 48x 48x 48x 48x 48x 48x 48x 48x 3154x 3154x 48x 3146x 3146x 48x 2x 2x 48x 3147x 3147x 3147x 3147x 48x 2103x 2103x 70x 48x 48x 48x 48x 48x 6264x 6264x 6264x 6264x 6264x 2061x 2061x 4203x 4171x 4138x 33x 33x 6264x 48x 3141x 3141x 3141x 3141x 3131x 3131x 3131x 10x 48x 8x 6x 12x 2x 1003x 8x 48x 48x 5x 5x 5x 4x 4x 4x 4x 4x 4x 1x 5x 48x 48x 48x 48x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 48x 2093x 2093x 2093x 2093x 2093x 2093x 2093x 2093x 48x 2033x 6x 6x 48x 9x 1x 8x 8x 8x 48x 1x 1x 1x 48x 4x 4x 4x 2x 2x 2x 4x 4x 4x 48x 4x 4x 4x 1x 3x 2x 2x 2x 2x 2x 1x 4x 48x 5x 5x 5x 5x 5x 10x 5x 1x 1x 5x 5x 5x 5x 5x 5x 1033x 1033x 1033x 1033x 5x 5x 5x 5x 48x 2x 48x 48x 1x 48x 7x 48x 8x 48x 48x 48x | import EventEmitter from 'events'
import KeyMap from './KeyMap'
import cloneDeep from 'lodash/cloneDeep'
import createHttpAdapter from './createHttpAdapter'
import fastDiff from './fastDiff'
import isArray from 'lodash/isArray'
import makeQueryKey from './makeQueryKey'
import mget from './mget'
import microTask from '@r14c/async-utils/microTask'
import rebase from './rebase'
import registerSchemas from './registerSchemas'
import toNumber from 'lodash/toNumber'
import uniqueId from './uniqueId'
import {register} from './registry'
import {
Map,
Stack,
fromJS,
isImmutable,
isKeyed
} from 'immutable'
const idRegex = /^[0-9a-z]+?-[0-9a-z]+$/i
/**
* @param {Object} data
* @private
*/
const convert = (data) => fromJS(data, (key, value) => {
return isKeyed(value)
? value.toMap()
: value.toList()
})
/**
* @param {Object} options
* @param {Object} options.models
* @param {String} [options.basePath=''] - default prefix for http requests
* @param {function} [options.adapter] - a custom fetch
* @param {function} [options.deserialize] - request post-processing
* @return {Store} a vdata store instance
*/
const createStore = (options = {}) => {
const evt = new EventEmitter()
const http = createHttpAdapter(options)
const models = cloneDeep(options.models)
const storeId = uniqueId(null, 1e5)
const queryCacheTimeout = options.cacheTimeout || 500 // evict query cache after 500ms by default
const keyMap = KeyMap.create()
let queryCache = {}
let store = registerSchemas(Map(), options.models)
const getBasePath = (collectionName) => {
const model = models[collectionName]
return model.basePath || options.basePath || ''
}
/**
* @param {String} id
* @private
*/
const resolveId = (collectionName, id) => {
const isTmp = idRegex.test(id)
return (isTmp) ? id : keyMap.get(collectionName, id)
}
/**
* @param {String} id
* @private
*/
const resolvePk = (collectionName, id) => {
const isTmp = idRegex.test(id)
return (isTmp) ? keyMap.get(collectionName, id) : id
}
/**
* @param {String} collectionName
* @param {Object} data
* @private
*/
const getMeta = (collectionName, data) => {
try {
const model = models[collectionName]
const idAttribute = model.idAttribute
return {
basePath: getBasePath(collectionName),
id: mget(data, '__tmp_id'),
idAttribute,
pk: mget(data, idAttribute),
symId: mget(data, '__sym_id')
}
} catch (e) {
throw new Error(`missing collection: ${collectionName}`)
}
}
/**
* queue a micro-task to broadcast the given message object
*
* @param {String} message
* @param {Object} options
* @param {Boolean} [options.quiet=false]
* @private
*/
const emit = (message, options = {}) => {
const quiet = options.quiet || false
if (quiet === false) {
microTask(() => evt.emit('all', message))
}
}
/**
* @constructor
*/
let Store = function () {
evt.setMaxListeners(0) // no limit
this.models = options.models
this.storeId = storeId
}
/**
* tag a javascript object with metadata that allows it to be tracked by the vdata store.
* `__tmp_id` and the `idAttribute` configured for the given collection are both used to
* identify the object. editing either of these will cause vdata to see the resulting
* object as something new that needs to be tracked separately from the original object.
*
* @param {String} collection
* @param {Object} [data={}]
* @return {Object}
*/
Store.prototype.createRecord = function (collectionName, data = {}) {
const model = models[collectionName]
const idAttribute = model.idAttribute
let pk = mget(data, idAttribute)
let id = mget(data, '__tmp_id')
if (pk && !id) {
id = keyMap.get(collectionName, pk) || uniqueId(storeId) // get or gen id
keyMap.link(collectionName, pk, id) // 2x link
} else if (!pk && id) {
// noop
} else if (pk && id) {
keyMap.link(collectionName, pk, id) // 2x link
} else Eif (!pk && !id) {
id = uniqueId(storeId) // gen id
}
return {...data, __tmp_id: id}
}
/**
* get a particular object from the store using the primary key provided by
* your api server, or the temporary local id that vdata uses internally to
* track records.
*
* @param {String} collectionName
* @param {String} pkOrId
* @return {Object}
*/
Store.prototype.get = function (collectionName, pkOrId) {
const id = resolveId(collectionName, pkOrId)
const versions = store.getIn([collectionName, id], Stack())
const record = versions.first()
if (record) {
const size = versions.size
const index = 0
return this.createRecord(collectionName, {
...record.toJS(),
__sym_id: `${index}-${size}`
})
} else {
return null
}
}
/**
* get all of the records in `collectionName`. if you include a `keys`
* parameter, this method returns all of the records that match the ids
* listed.
*
* @param {String} collectionName
* @param {string[]} [keys]
* @return {object[]}
*/
Store.prototype.getList = function (collectionName, keys) {
let result
if (isArray(keys)) {
result = (keys.length)
? keys.map((key) => this.get(collectionName, key))
: []
} else {
result = store
.get(collectionName)
.keySeq()
.map((key) => this.get(collectionName, key))
.toJS()
}
return result
}
/**
* @ignore
*/
Store.prototype.getAll = function () {
return this.getList.apply(this, arguments)
}
/**
* remove a record from the store, identified by public key or temporary id.
*
* @emits Store#remove
* @param {String} collectionName
* @param {String} pkOrId
* @param {Object} options
* @param {Boolean} options.quiet
* @return {Object}
*/
Store.prototype.remove = function (collectionName, pkOrId, options = {}) {
const id = resolveId(collectionName, pkOrId)
let object = this.get(collectionName, id)
if (object) {
const meta = getMeta(collectionName, object)
store = store.removeIn([collectionName, id])
keyMap.unlink(collectionName, meta.pk, meta.id)
delete object.__tmp_id
delete object.__sym_id
emit({
collectionName,
event: 'remove',
record: object
}, {
quiet: options.quiet
})
} else Iif (process.env.NODE_ENV !== 'test') {
console.warn(
`[@citygro/vdata] attempting to remove a record that is not tracked by Store#${storeId}`,
{collectionName, pkOrId, options}
)
}
return object
}
/**
* remove all of the records in `collectionName` or all of the records that match the ids passed into `keys`.
*
* @emits Store#remove-list
* @param {String} collectionName
* @param {string[]} keys
* @return {object[]}
*/
Store.prototype.removeList = function (collectionName, keys, options = {}) {
const records = this.getAll(collectionName, keys).map((record) => {
const {id} = getMeta(collectionName, record)
return this.remove(collectionName, id, {quiet: true})
})
emit({
collectionName,
event: 'remove-list',
records
}, {
quiet: options.quiet
})
return records
}
/**
* @ignore
*/
Store.prototype.removeAll = function () {
return this.removeList.apply(this, arguments)
}
/**
* remove all records from all collections
* @emits Store#remove-list
*/
Store.prototype.clear = function () {
store.keySeq().forEach((collectionName) => {
this.removeAll(collectionName)
})
}
/**
* vdata automatically tracks all of the versions that are created for every
* record that it tracks. this version tracking is how `Store#rebase` is able
* to implement a simple Observed-Remove Set (ORSet) that enables vdata to
* deterministically merge all of the changes to a particular record.
*
* given `data` with a particular `__sym_id` and the current version of the
* same record at `data[idAttribute]`, return a merged record containing all
* changes, applied to the base record at `__sym_id` in the following order,
* diff'd against `base`:
*
* 1. current
* 2. data
*
* at CityGro we use the ORSet implementation in vdata to power the real-time
* features of our customer portal application. in most cases, the core
* diffing algorithm is able to generate merged outputs with intuitive
* results. however, it is important to note the rules that we use to
* resolve certain edge cases.
*
* 1. Last-write (from the perspective of the writer) wins. in our
* experience, this produces the least surprising results for our users.
* 2. Array mutations are all-or-nothing. we currently don't have an
* acceptable solution to merging arrays with arbitrary mutations.
* following rule #1, we opt to *replace* any previous values with the
* latest version of the array. if you have thoughts on this, please open
* a ticket on [GitLab](https://gitlab.com/citygro/vdata/issues).
*
* @param {String} collection
* @param {Object} data
* @return {Object}
*/
Store.prototype.rebase = function (collectionName, data) {
const record = (isImmutable(data)) ? data.toJS() : data
const {id} = getMeta(collectionName, record)
let base = null
Eif (record.__sym_id) {
const [index, size] = record.__sym_id.split('-').map(toNumber)
const offset = (index - size)
const versions = store.getIn([collectionName, id])
Eif (versions) {
base = versions.get(offset).toJS()
}
}
const current = this.get(collectionName, id)
const object = (base || current)
? rebase(base, current, record)
: record
return object
}
/**
* add a record to the store. you *do not* need to pass your data to
* `Store#createRecord` before adding it.
*
* @emits Store#add
* @see {Store.rebase}
* @param {String} collection
* @param {Object} data
* @param {Object} options
* @param {Boolean} [options.quiet=false] silence store events for this invocation
* @return {Object}
*/
Store.prototype.add = function (collectionName, data, options = {}) {
const record = this.createRecord(collectionName, data)
const latest = convert(record)
const {id} = getMeta(collectionName, latest)
const versions = store.getIn([collectionName, id], Stack())
store = store.setIn([collectionName, id], versions.unshift(latest))
const object = this.get(collectionName, id)
emit({
collectionName,
event: 'add',
record: object
}, {
quiet: options.quiet
})
return object
}
/**
* add all of the records in `data` to `colectionName` in a single operation.
*
* @emits Store#add-list
* @param {String} collectionName
* @param {Array<Object>} data
* @return {Array<Object>}
*/
Store.prototype.addList = function (collectionName, data, options = {}) {
const records = data.map((item) => this.add(collectionName, item, {quiet: true}))
emit({
collectionName,
event: 'add-list',
records
}, {
quiet: options.quiet
})
return records
}
/**
* check if `data` differs from the current version of the corresponding
* record in the store.
*
* @param {String} collectionName
* @param {Object} data
* @return {Boolean}
*/
Store.prototype.hasChanges = function (collectionName, data) {
if (!data) {
return false
} else {
const {id} = getMeta(collectionName, data)
const record = this.get(collectionName, id) || {}
return fastDiff(
{
...record,
__sym_id: null
},
{
...data,
__sym_id: null
}
)
}
}
/**
* send a `DELETE` request to the endpoint configured for `collectionName`
* and remove the corresponding record from the store.
*
* @async
* @emits Store#remove
* @param {String} collectionName
* @param {Object} data
* @param {Object} options
* @return {Promise<Object>}
*/
Store.prototype.destroy = function (collectionName, data, options = {}) {
const {id, pk, basePath} = getMeta(collectionName, data)
return http({
url: `${basePath}/${collectionName}/${pk}`,
method: 'DELETE',
...options
})
.then(() => microTask(() => this.remove(collectionName, id)))
}
/**
* persist `data` using the endpoint configured for `collectonName`. if
* `data` is *only* identified by a local temporary id send a `POST` request to
* `/:basePath/:collectionName`. if `data` has a primary key send a `PUT`
* request to `/:basePath/:collectionName/:primaryKey`
*
* when updating an existing record, this methods calls Store#rebase.
* this gives vdata some important super-powers that you can use to build
* real-time applications. check the method's docs for details.
*
* @async
* @emits Store#add
* @param {String} collection
* @param {Object} data
* @param {Object} options
* @return {Promise<Object>}
*/
Store.prototype.save = function (collectionName, data, options = {}) {
const {id, pk, basePath} = getMeta(collectionName, data)
let promise
let request = {...options}
if (this.isValidId(pk)) {
request.method = 'PUT'
promise = http({
...request,
url: `${basePath}/${collectionName}/${pk}`,
method: 'PUT',
body: {
...this.rebase(collectionName, data),
__tmp_id: undefined,
__sym_id: undefined
}
})
} else {
promise = http({
...request,
url: `${basePath}/${collectionName}`,
method: 'POST',
body: {
...data,
__tmp_id: undefined,
__sym_id: undefined
}
})
}
return promise.then((data) => {
const object = (id) ? {...data, __tmp_id: id} : data
return microTask(() => this.add(collectionName, object))
})
}
/**
* fetch a particular record from `/:basePath/:collectionName/:primaryKey`.
* if `force === false` immediately return the cached record if present.
*
* @async
* @param {String} collection
* @param {Object} [query]
* @param {Object} [options]
* @param {Boolean} [options.force=false]
* @return {Promise<Object>}
*/
Store.prototype.find = function (collectionName, id, options = {}) {
let promise
const force = options.force || false
const data = this.get(collectionName, id)
if (!this.isValidId(id)) {
promise = Promise.resolve(null)
} else if (!data || force === true) {
const pk = resolvePk(collectionName, id)
const basePath = this.getBasePath(collectionName)
const request = {
url: `${basePath}/${collectionName}/${pk}`,
method: 'GET',
...options
}
promise = http(request)
.then((data) => microTask(() => this.add(collectionName, data)))
} else {
promise = Promise.resolve(data)
}
return promise
}
/**
* fetch all of the records from the api that match the parameters specified
* in `query`. these are sent along with the request as query parameters.
* if `force === false` immediately return a cached response if one exists.
*
* @async
* @param {String} collection
* @param {Object} [query]
* @param {Object} [options]
* @return {Promise<Array<Object>>}
*/
Store.prototype.findAll = function (collectionName, query, options = {}) {
let promise
const force = options.force || false
const ttl = options.ttl || queryCacheTimeout
const basePath = this.getBasePath(collectionName)
const key = makeQueryKey(collectionName, query, options)
const cachedKeys = queryCache[key] || []
let data = this.getList(collectionName, cachedKeys).filter((record) => !!record)
if (data.length !== cachedKeys.length) {
delete queryCache[key]
data = []
}
Eif (!data.length || force === true) {
const request = {
url: `${basePath}/${collectionName}`,
method: 'GET',
params: query,
...options
}
promise = http(request)
.then((result) => microTask(() => {
let resultKeys = []
const records = result.map((data) => {
const record = this.createRecord(collectionName, data)
const {id} = getMeta(collectionName, record)
resultKeys.push(id)
return record
})
queryCache[key] = resultKeys
setTimeout(() => {
delete queryCache[key]
}, ttl)
return this.addList(collectionName, records)
}))
} else {
promise = Promise.resolve(data)
}
return promise
}
/**
* bind an event listener to the store
*
* @param {String} event
* @param {function} handler
*/
Store.prototype.on = function (event, handler) {
evt.addListener(event, handler)
}
/**
* unbind an event listener to the store
*
* @param {String} event
* @param {function} handler
*/
Store.prototype.off = function (event, handler) {
evt.removeListener(event, handler)
}
/**
* manually emit a message using the store's event bus
*
* @param {String} event
* @param {*} payload
*/
Store.prototype.emit = function (event, payload) {
microTask(() => evt.emit(event, payload))
}
/**
* get the base path for `collectionName`
*
* @param {String} collectionName
* @return {String}
*/
Store.prototype.getBasePath = (collectionName) => {
return getBasePath(collectionName)
}
/**
* check if the given value is a valid id
*
* @param {*} id
* @return {Boolean}
*/
Store.prototype.isValidId = (id) => {
return id !== null && id !== undefined && id !== ''
}
const storeInstance = new Store()
Iif (process.env.NODE_ENV !== 'test') {
console.log('[@citygro/vdata] store ready!', storeInstance, options)
}
return register(storeInstance)
}
/**
* @module Store
*/
export default createStore
|