Skip to content

Latest commit

 

History

History
1181 lines (797 loc) · 33.1 KB

api.md

File metadata and controls

1181 lines (797 loc) · 33.1 KB

clay-resource@5.7.2

Resource accessor for ClayDB

Functions

create(args) -> ClayResource

Create a ClayResource instance

Param Type Description
args *

fromDriver(driver, nameString, options) -> ClayResource

Create clayResource class from driver

Param Type Description
driver Driver Driver to bind
nameString string Resource name string
options Object Optional settings

Example:

const { fromDriver } = require('clay-resource')
const { SqliteDriver } = require('clay-driver-sqlite')
{
  let driver = new SqliteDriver('var/test.db')
  let resource = fromDriver(driver)
}

ClayResource Class

Resource accessor

Extends:

  • AnnotateMixed
  • CloneMixed
  • InboundMixed
  • OutboundMixed
  • PolicyMixed
  • RefMixed
  • SubMixed
  • ThrowMixed
  • InternalMixed
  • PrepareMixed
  • DecorateMixed
  • CacheMixed
  • ConditionMixed
  • ClusterMixed

new ClayResource(nameString, bounds, options)

Constructor of ClayResource class

Param Type Description
nameString string Name string
bounds Object.<string, function()> Method bounds
options Object Optional settings
options.annotates boolean Enable annotation
options.refs Array.<ClayResource> Add resource refs

resource.one(id, options, ) -> Promise.<Entity>

Get a resource

Param Type Description
id ClayId Id of the entity
options Object Optional settings
options.ignoreCached boolean Ignore cached data
options.strict boolean If true, throws an error when not found
options.plain boolean Mark result as plain object

Example:

const Product = lump.resource('Product')
async function tryOne () {
  const product = await Product.one(1) // Find by id
  console.log(product)
}

resource.list(condition, options, ) -> Promise.<Collection>

List entities from resource

Param Type Description
condition ListCondition List condition query
condition.filter FilterTerm Filter condition
condition.page PagerTerm Page condition
condition.page.number number Number of page, start with 1
condition.page.size number Number of resources per page
condition.sort SortTerm Sort condition
options Object Optional settings

Example:

const Product = lump.resource('Product')
async function tryList () {
  const products = await Product.list({
    filter: { type: 'Vehicle' },  // Filter condition
    page: { number: 1, size: 25 }, // Paginate
    sort: [ 'createdAt', '-name' ] // Sort condition
  })
  console.log(products)
}
tryList()

resource.create(attributes, options) -> Promise.<Entity>

Create a new entity with resource

Param Type Description
attributes Object Resource attributes to create
options Object Optional settings
options.allowReserved boolean Arrow to set reserved attributes (like "id")
options.errorNamespace string Namespace for error fields
options.waitListeners boolean Wait for listeners

Example:

const Product = lump.resource('Product')
async function tryCreate () {
  const product = await Product.create({
    name: 'Super Car',
    type: 'Vehicle'
  })
  console.log(product)
}
tryCreate()

resource.update(id, attributes, options) -> Promise.<Entity>

Update an existing entity in resource

Param Type Description
id ClayId Resource id
attributes Object Resource attributes to update
options Object Optional settings
options.allowReserved boolean Arrow to set reserved attributes (like "id")
options.errorNamespace string Namespace for error fields
options.waitListeners boolean Wait for listeners

Example:

const Product = lump.resource('Product')
async function tryUpdate () {
  const product = await Product.update(1, {
    name: 'Super Super Car'
  })
  console.log(product)
}
tryUpdate()

resource.destroy(id, options) -> Promise.<number>

Delete a entity resource

Param Type Description
id ClayId Resource id
options Object Optional settings
options.waitListeners boolean Wait for listeners

Example:

const Product = lump.resource('Product')
async function tryDestroy () {
  await Product.destroy(1)
}
tryDestroy()

resource.drop(options) -> Promise.<boolean>

Drop resource

Param Type Description
options Object Optional settings
options.waitListeners boolean Wait for listeners

Example:

const Product = lump.resource('Product')
async function tryDrop () {
  await Product.drop()
}
tryDrop()

resource.oneBulk(ids, options) -> Promise.<Object.<ClayId, Entity>>

One as bulk

Param Type Description
ids Array.<ClayId> Resource ids
options Object Optional settings

Example:

const Product = lump.resource('Product')
async function tryOneBulk () {
  const products = await Product.oneBulk([ 1, 5, 10 ])
  console.log(products)
}
tryOneBulk()

resource.listBulk(conditionArray) -> Promise.<Array.<Collection>>

List with multiple conditions

Param Type Description
conditionArray Array.<ListCondition>

Example:

const Product = lump.resource('Product')
async function tryListBulk () {
  const [ cars, ships ] = await Product.listBulk([
    { filter: { type: 'CAR' } },
    { filter: { type: 'SHIP' } },
  ])
  console.log(cars)
  console.log(ships)
}
tryListBulk()

resource.createBulk(attributesArray, options) -> Promise.<Array.<Entity>>

Create multiple resources

Param Type Description
attributesArray Array.<Object> List of attributes
options Object Optional settings
options.allowReserved boolean Arrow to set reserved attributes (like "id")
options.errorNamespace string Namespace for error fields
options.waitListeners boolean Wait for listeners

Example:

const Product = lump.resource('Product')
async function tryCreateBulk () {
  const products = await Product.createBulk([
    { name: 'Super Orange', type: 'CAR' },
    { name: 'Ultra Green', type: 'CAR' },
  ])
  console.log(products)
}
tryCreateBulk()

resource.updateBulk(attributesHash, options) -> Promise.<Object.<ClayId, Entity>>

Update multiple resources

Param Type Description
attributesHash Object.<ClayId, Object> Hash of attributes
options Object Optional settings
options.allowReserved boolean Arrow to set reserved attributes (like "id")
options.errorNamespace string Namespace for error fields
options.waitListeners boolean Wait for listeners

Example:

const Product = lump.resource('Product')
async function tryUpdateBulk () {
  const products = await Product.updateBulk({
    '1': { name: 'Super Super Orange' },
    '2': { name: 'Ultra Ultra Green' },
  })
  console.log(products)
}
tryUpdateBulk()

resource.destroyBulk(ids, options) -> Promise.<number>

Update multiple resources

Param Type Description
ids Array.<ClayId> Ids to destroy
options Object Optional settings

Example:

const Product = lump.resource('Product')
async function tryDestroyBulk () {
  await Product.destroyBulk([1, 2])
})
tryDestroyBulk()

resource.cursor(condition, options) -> Object

Create cursor to cursor

Param Type Description
condition Object Search condition
condition.filter FilterTerm Filter condition
condition.sort SortTerm Sort condition
options Object Optional settings

Example:

const Product = lump.resource('Product')
async function tryCursor () {
  const cursor = await Product.cursor({
    filter: { type: 'CAR' }
  })
  console.log(cursor.length) // Number of entities matches the condition
  for (const fetch of cursor) {
    const car = await fetch() // Fetch the pointed entity
    console.log(car)
  }
}
tryCursor()

resource.each(handler, condition, options) -> Promise

Iterate entities with handler

Param Type Description
handler function Entity handler
condition Object Optional settings
condition.filter FilterTerm Filter condition
condition.sort SortTerm Sort condition
options Object Optional settings

Example:

const Product = lump.resource('Product')
async function tryEach () {
   await Product.each(async (product) => {
      // Do something with each entity
   }, {
      filter: {price: {$gt: 100}}
   })
}
tryEach()

resource.first(filter, options) -> Promise.<?Entity>

Get the first entity matches filter

Param Type Description
filter FilterTerm Listing filter
options Object Optional settings
options.sort Object Sort conditions

Example:

const Product = lump.resource('Product')
async function tryFirst () {
  const product = Product.first({ name: 'Super Super Orange' })
  console.log(product)
}
tryFirst()

resource.last(filter, options) -> Promise.<?Entity>

Get the last entity matches filter

Param Type Description
filter FilterTerm Listing filter
options Object Optional settings
options.sort Object Sort conditions

resource.only(filter, options) -> Promise.<?Entity>

Almost same with .first(), but throws an error if multiple record hits, or no record found

Param Type Description
filter FilterTerm Listing filter
options Object Optional settings
options.strict boolean If true, throws an error when not found

Example:

const Product = lump.resource('Product')
async function tryOnly () {
  const product = Product.only({ name: 'Super Super Orange' })
  console.log(product)
}
tryOnly()

resource.seal(privateKey, options) -> Promise

Seal resources

Param Type Description
privateKey string RSA Private key
options Object Optional settings
options.by string For $$by

Example:

const Product = lump.resource('Product')
const privateKey = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
async function trySeal () {
  await Product.seal(privateKey)
}
trySeal()

resource.has(id) -> Promise.<boolean>

Check entity with id exists

Param Type Description
id ClayId Id of the entity

Example:

const Product = lump.resource('Product')
async function tryHas () {
  const has = await Product.has(1)
  console.log(has)
}
tryHas()

resource.exists(filter) -> Promise.<boolean>

Check data exists with filter

Param Type Description
filter FilterTerm List filter

Example:

const Product = lump.resource('Product')
async function tryExists () {
  const exists = await Product.exists({ name: 'Super Super Orange' })
  console.log(exists)
}
tryExists()

resource.count(filter) -> Promise.<number>

Count data matches filter

Param Type Description
filter FilterTerm List filter

Example:

const Product = lump.resource('Product')
async function tryCount () {
  const count = await Product.count({ type: 'CAR' })
  console.log(count)
}
tryCount()

resource.of(attributes)

Find entity with attributes and returns if found. If not found, create and return the one.

Param Type Description
attributes Object Attributes

Example:

const Product = lump.resource('Product')
async function tryOf () {
  const values = await Product.of({ code: '#1234' })
  console.log(values)
}
tryOf()

resource.all(filter, options, ) -> Promise.<Array.<ClayEntity>>

Get all entities inside resource which matches the filter

Param Type Description
filter FilterTerm Listing filter
options Object Optional settings
options.sort string,Array.<string> Sort attribute
options.iterateSize number Size to iterate

resource.refOf(id) -> string

Get resource ref string for this resource

Param Type Description
id ClayId,string Resource id

resource.toggleAnnotate()

resource.clone() -> Object

Clone the instance

resource.addInbound(name, inbound) -> InboundMixed

Add inbound

Param Type Description
name string Name of inbound
inbound function Inbound function

resource.hasInbound(name) -> boolean

Check if has inbound

Param Type Description
name string Name of inbound

resource.removeInbound(name) -> InboundMixed

Remove inbound

Param Type Description
name string Name of inbound

resource.applyInbound(attributesArray, actionContext) -> Promise.<Array.<EntityAttributes>>

Apply inbound to array of attributes

Param Type Description
attributesArray Array.<EntityAttributes> Array of attributes
actionContext ActionContext Context for resource action

resource.inboundAttributes(attributes, actionContext) -> Promise.<EntityAttributes>

Inbound attributes

Param Type Description
attributes EntityAttributes Attributes to inbound
actionContext ActionContext Context for resource action

resource.inboundAttributesArray(attributesArray, actionContext) -> Promise.<Array.<EntityAttributes>>

Inbound attributes array

Param Type Description
attributesArray Array.<EntityAttributes> Attributes array to inbound
actionContext ActionContext Context for resource action

resource.inboundAttributesHash(attributesHash, actionContext) -> Promise.<AttributesHash>

Inbound attributes hash

Param Type Description
attributesHash AttributesHash
actionContext ActionContext Context for resource action

resource.addOutbound(name, handler) -> OutboundMixed

Add outbound

Param Type Description
name string Name of outbound
handler function Format handler function

resource.hasOutbound(name) -> boolean

Check if has outbound

Param Type Description
name string Name of outbound

resource.removeOutbound(name) -> OutboundMixed

Remove outbound

Param Type Description
name string Name of outbound

resource.applyOutbound(entities, actionContext) -> Promise.<Array.<Entity>>

Apply outbound to entities

Param Type Description
entities Array.<Entity> Entities to outbound
actionContext Object

resource.outboundEntity(entity, actionContext) -> Promise.<Entity>

Format entity

Param Type Description
entity Entity
actionContext Object

resource.outboundEntityArray(entityArray, actionContext) -> Promise.<Array.<Entity>>

Proses entity array

Param Type Description
entityArray Array.<Entity>
actionContext Object

resource.outboundCollection(collection, actionContext) -> Promise.<Collection>

Format entity collection

Param Type Description
collection Collection
actionContext Object

resource.outboundEntityHash(entityHash, actionContext) -> Promise.<EntityHash>

Format entity hash

Param Type Description
entityHash EntityHash
actionContext Object

resource.outboundCollectionArray(collectionArray, actionContext) -> Promise.<CollectionArray>

Format collection array

Param Type Description
collectionArray CollectionArray
actionContext Object

resource.getPolicy() -> ClayPolicy

Get the policy

resource.setPolicy(policy) -> PolicyMix

Set policy

Param Type Description
policy

resource.removePolicy()

Remove policy

resource.fetchPolicy(digest) -> Promise.<ClayPolicy>

Fetch policy from db

Param Type Description
digest string

resource.savePolicy(policy) -> Promise.<string>

Save policy

Param Type Description
policy ClayPolicy

resource.addRef(resourceName, resource)

Add resource ref

Param Type Description
resourceName string
resource ClayResource

resource.hasRef(resourceName) -> boolean

Has resources ref

Param Type Description
resourceName string

resource.getRef(resourceName) -> boolean

Get resource ref

Param Type Description
resourceName string

resource.removeRef(resourceName) -> RefMixed

Remove resource ref

Param Type Description
resourceName string

resource.sub(name) -> ClayResource

Get sub resource

Param Type Description
name string

resource.subNames() -> Promise.<Array.<string>>

Get names of sub resources

resource.throwEntityNotFoundError(id)

Throw entity not found error

Param Type Description
id ClayId

resource.internal(name) -> ClayResource

Get internal resource

Param Type Description
name string

resource.internalNames() -> Promise.<Array.<string>>

Get names of internal resources

resource.prepares(prepares) -> PrepareMixed

Toggle prepare support

Param Type Description
prepares boolean Should prepare or not

resource.prepareIfNeeded() -> Promise

Do prepare if needed

resource.prepare() -> Promise.<Object>

Do preparing

resource.addPrepareTask(name, task) -> PrepareMixed

Add prepare task

Param Type Description
name string Name of task
task function Task function

resource.hasPrepareTask(name) -> boolean

Check if has task

Param Type Description
name string

resource.removePrepareTask(name) -> PrepareMixed

Remove a task

Param Type Description
name string Name of task

resource.setNeedsPrepare(needsPrepare) -> PrepareMixed

Set needs prepare

Param Type Description
needsPrepare boolean Needs preparing

resource.decorate(methodName, decorate) -> DecorateMixed

Decorate a method

Param Type Description
methodName string Name of method
decorate function Decorate function

resource.caches(caches) -> CacheMixed

Toggle caching

Param Type Description
caches boolean Should cache or not

resource.storeCache(entity)

Store an entity into cache

Param Type Description
entity

resource.gainCache(id)

Gain entity from cache

Param Type Description
id ClayId

resource.removeCache(id)

Remove entity from cache

Param Type Description
id ClayId

resource.requestCacheClear(ids)

Request cache clear

Param Type Description
ids ClayId,Array.<ClayId> Ids to clear

resource.parseCondition(condition) -> ListCondition

Parse list condition

Param Type Description
condition ListCondition

resource.parseConditionArray(conditionArray) -> Array.<ListCondition>

Parse list condition array

Param Type Description
conditionArray Array.<ListCondition>