@lgslabs/bits-memory-crud v3.1.2
BITS Memory CRUD
The implementation of in-memory CRUD for BITS. This package extends the functionality provided in bits-core. All items in the collection are expected to be properly-formatted JSON objects with at least an id field.
Use
Importing
npm install @lgslabs/bits-memory-crudconst {CrudService, CrudManager, CrudMessenger, CrudRouter, CrudApi} = require('@lgslabs/bits-memory-crud');Service
The Service is responsible for creating, loading, and unloading the manager, messenger, router (if desired), a public API (if desired), and any resources the subsystem may need.
load
Loads the Service, thereby creating and loading the other subsystem components with the provided options
load({messageCenter, tag, scopes, readScopes, writeScopes, filter, routePath, routerFilepath, apiExport, apiData, ...args})messageCenterMessageCenter The MessageCenter to usetagString The tag to use for requests/eventsscopesArray The scopes to use on requests/eventsreadScopesArray The scopes for read-type requests/eventswriteScopesArray The scopes for write-type requestsfilterBoolean True if the Messenger should filter CRUD events, false otherwiseroutePathString The path to use for the router (optional)routerFilepathString The path to the Router class to use (optional)apiExportSymbol(API_EXPORT) How to export the API. This must be a value from API_EXPORT object in order to exportapiDataObject The data to supply for export ({name, filepath}forGLOBAL,{topic, value}forRESOURCE)...argsAny number of additional key/value pairs- Returns Promise resolving to request or rejecting to error
createManager
Called in the Service's load function to create the manager. By default, it creates an instance of the base implementation of the CRUD manager. If the subsystem needs additional functionality, it is recommended to override this function.
createManager()- Returns Promise resolving to request or rejecting to error
createMessenger
Called in the Service's load function to create the messenger. By default, it creates an instance of the base implementation of the CRUD messenger. If the subsystem needs additional functionality, it is recommended to override this function.
createMessenger()- Returns Promise resolving to request or rejecting to error
Manager
The Manager is responsible for performing any operations related to the subsystem. It has default implementations for all CRUD operations. The manager is an EventEmitter to allow communication with the Messenger. To change the Manager class being used, override the createManager function in the Service to create and return the desired Manager implementation. The loadManager and unloadManager functions can be overridden in the event more customization is required.
_createId
Helper function to create an ID for the item to be added. By default, IDs are strings.
_createId(item)itemObject The item to be created- Returns Promise resolving to the ID or rejecting to error
validate
Helper function to perform any necessary validation on the item. By default, the function ensures the item is a non-null object.
validate(item)itemObject The item to validate- Returns Promise resolving to the validated item or rejecting to error
create
Creates the provided item(s). The function allows a single item OR an array of items to be passed.
create(item)itemObject|Array The item(s) to add to the collection- Returns Promise resolving to the created item(s) or rejecting to error
- Emits
createdwith an array of the created item(s)
_create
Helper function to create a single item.
_create(item)itemObject The item to create- Returns Promise resolving to the item to add to the collection or rejecting to error
update
Applies the provided update to the specified ID(s). NOTE This function does NOT perform a deep update.
update(id, update)idString|Array the ID(s) of the item(s) to apply the updateupdateObject the update to apply- Returns Promise resolving to the updated item(s) or rejecting to error
- Emits
updatedwith an array of the updated item(s)
_update
Helper function to update a single item
_update(id, update)idString the ID of the item to apply the updateupdateObject the update to apply- Returns Promise resolving to the updated item or rejecting to error
delete
Removes the item(s) holding the specified ID(s).
delete(id)idString|Array the ID(s) of the item(s) to remove- Returns Promise resolving to the deleted item(s) or rejecting to error
- Emits
deletedwith an array of the deleted item(s)
_delete
Helper function to delete a single item
_delete(id)idString the ID of the item to remove- Returns Promise resolving to the deleted item or rejecting to error
upsert
Upserts the item(s).
upsert(item)itemObject|Array the ID(s) of the item(s) to remove- Returns Promise resolving to the deleted item(s) or rejecting to error
- Emits
createdwith an array of the created item(s), if any - Emits
updatedwith an array of the updated item(s), if any
_upsert
Helper function to upsert a single item
_upsert(item)itemObject the item to upsert- Returns Promise resolving to an object containing
itemandevent(created|updated), or rejecting to error
_upsertFilter
Helper function that attempts to retrieve an existing item matching some criterion. By default, this function matches on the id property.
_upsertFilter(item)itemObject the item to upsert- Returns Promise resolving to an object, or rejecting to error
list
Retrieves the entire collection of items
list(query, options)queryObject unusedoptionsObject unused- Returns Promise resolving to an array of items or rejecting to error
count
Retrieves the number of items in the collection.
count(query)queryObject unused in implementation- Returns Promise resolving to the item count or rejecting to error
get
Retrieves a specific item from the collection
get(id)idString the ID of the item to retrieve- Returns Promise resolving to the specified item or rejecting to error
Messenger
The Messenger is responsible for interacting with the MessageCenter for request handling, event subscriptions, and publishing events. It has default implementations for all CRUD requests and events, including event filtering if options.filter is true. To change the Messenger class being used, override the createMessenger function in the Service to create and return the desired Messenger implementation. The loadMessenger and unloadMessenger functions can be overridden in the event more customization is required.
load
Loads the Messenger. This is where all initialization should be done, and how the Messenger should receive any additional parameters.
load({filter, ...options})filterBoolean True if the Messenger should filter CRUD events, false otherwiseoptionsObject The rest of the options passed into the Service'sloadfunction- Returns Promise resolving to request or rejecting to error
sanitize
Removes any sensitive information from the object.
sanitize(item)itemObject the item to sanitize- Returns Promise resolving to the sanitized item or rejecting to error
filterCreated
Filters the created item(s) based on the subscribed user
filterCreated(user, items)userObject the user to use for filtering conditionsitemsArray the items for filtering- Returns Promise resolving to the filtered items or rejecting to error
filterUpdated
Filters the updated item(s) based on the subscribed user
filterUpdated(user, items)userObject the user to use for filtering conditionsitemsArray the items for filtering- Returns Promise resolving to the filtered items or rejecting to error
filterDeleted
Filters the deleted item(s) based on the subscribed user
filterDeleted(user, items)userObject the user to use for filtering conditionsitemsArray the items for filtering- Returns Promise resolving to the filtered items or rejecting to error
_create
Handles incoming create requests, forwarding them to the manager and sanitizing the result.
_create(metadata, item)metadataObject information created by the MessageCenter about the requestitemObject|Array the item(s) to create- Returns Promise resolving to the created items, after being sanitized, or rejecting to error
_update
Handles incoming update requests, forwarding them to the manager and sanitizing the result.
_update(metadata, ids, update)metadataObject information created by the MessageCenter about the requestidString|Array the ID(s) of the item(s) to apply the updateupdateObject the update to apply- Returns Promise resolving to the updated items, after being sanitized, or rejecting to error
_delete
Handles incoming delete requests, forwarding them to the manager and sanitizing the result.
_delete(metadata, id)metadataObject information created by the MessageCenter about the requestidString|Array the ID(s) of the item(s) to remove- Returns Promise resolving to the deleted items, after being sanitized, or rejecting to error
_list
Handles incoming list requests, forwarding them to the manager and sanitizing the result.
_list(metadata, query, options)metadataObject information updated by the MessageCenter about the requestqueryObject unusedoptionsObject unused- Returns Promise resolving to the items in the collection, after being sanitized, or rejecting to error
_count
Handles incoming count requests, forwarding them to the manager.
_count(metadata, query)metadataObject information updated by the MessageCenter about the requestqueryObject unused- Returns Promise resolving to the number of items in the collection or rejecting to error
_get
Handles incoming get requests, forwarding them to the manager and sanitizing the result.
_get(metadata, id)metadataObject information created by the MessageCenter about the requestidString the ID of the item to retrieve- Returns Promise resolving to the deleted items, after being sanitized, or rejecting to error
_created
Handles the created event emitted from the manager. If options.filter was true, it sends the created event with null scopes, then with read scopes to the subscribed user(s)
_created(item)itemsObject|Array the created item(s)
_updated
Handles the updated event emitted from the manager. If options.filter was true, it sends the updated event with null scopes, then with read scopes to the subscribed user(s)
_updated(item)itemsObject|Array the updated item(s)
_deleted
Handles the deleted event emitted from the manager. If options.filter was true, it sends the deleted event with null scopes, then with read scopes to the subscribed user(s)
_deleted(item)itemsObject|Array the deleted item(s)
Router
The Router is responsible for creating RESTful endpoints and handling any requests made. It has default endpoints for all CRUD operations. The Router is not intended to be created explicitly, but intended to be loaded as a resource for BaseServer to utilize. BaseServer will create an instance and add the middleware on the path provided. A Router is not required and will only be created if the routePath option is passed to Service.load.
Endpoints
- Create POST
<routePath>/create - Update POST
<routePath>/update - Delete POST
<routePath>/delete - List GET
<routePath>/list - Get GET
<routePath>/get - Count GET
<routePath>/count
_create
Calls create on the subsystem's API with the item(s) provided in the request's body.
_create(req, res, next)reqexpress.Request the request objectresexpress.Response the response objectnextFunction signals to express the continue down the middleware stack
_update
Calls update on the subsystem's API with the ID(s) and update provided in the request's body.
_update(req, res, next)reqexpress.Request the request objectresexpress.Response the response objectnextFunction signals to express the continue down the middleware stack
_delete
Calls delete on the subsystem's API with the ID(s) provided in the request's body.
_delete(req, res, next)reqexpress.Request the request objectresexpress.Response the response objectnextFunction signals to express the continue down the middleware stack
_list
Calls list on the subsystem's API with the query and options provided as query parameters, if any.
_list(req, res, next)reqexpress.Request the request objectresexpress.Response the response objectnextFunction signals to express the continue down the middleware stack
_get
Calls get on the subsystem's API with the ID provided as a query parameter, if any.
_get(req, res, next)reqexpress.Request the request objectresexpress.Response the response objectnextFunction signals to express the continue down the middleware stack
_count
Calls count on the subsystem's API with the query provided as a query parameter, if any.
_count(req, res, next)reqexpress.Request the request objectresexpress.Response the response objectnextFunction signals to express the continue down the middleware stack
API
The API allows other modules to call the functions of the current subsystem. It has default implementations for all CRUD operations, as well as adding and removing CRUD event listeners. Not all functions in the Manager need to be exposed in the API. An API is not required and will not be created unless both apiExport and apiData are supplied and valid.
constructor
constructor(options)optionsObject The options passed into the Service'sloadfunction
create
Sends a create request
create(item)itemObject|Array The item(s) to add to the collection- Returns Promise resolving to the created item(s) or rejecting to error
update
Sends an update request
update(id, update)idString|Array the ID(s) of the item(s) to apply the updateupdateObject the update to apply- Returns Promise resolving to the updated item(s) or rejecting to error
delete
Sends a delete request
delete(id)idString|Array the ID(s) of the item(s) to remove- Returns Promise resolving to the deleted item(s) or rejecting to error
list
Sends a list request
list(query, options)queryObject A query specifying which items to list- NOTE
querymay be unused in some implementations optionsObject The options to use when curating the list- NOTE
optionsmay be unused in some implementations - NOTE format of
optionsmay vary between implementations - Returns Promise resolving to an array of the items or rejecting to error
count
Sends a count request
count(query)queryObject A query specifying which items to count- NOTE
querymay be unused in some implementations - Returns Promise resolving to the item count or rejecting to error
get
Sends a get request
get(id)idString the ID of the item to retrieve- Returns Promise resolving to the specified item or rejecting to error
addCreatedListener
Adds a listener for the subsystem's created event
addCreatedListener(listener)listenerFunction the function to execute oncreated- Returns Promise resolving to request or rejecting to error
removeCreatedListener
Removes a listener for the subsystems created event
removeCreatedListener(listener)listenerFunction the function to remove- Returns Promise resolve to request or rejecting to error
addUpdatedListener
Adds a listener for the subsystem's updated event
addUpdatedListener(listener)listenerFunction the function to execute onupdated- Returns Promise resolving to request or rejecting to error
removeUpdatedListener
Removes a listener for the subsystems updated event
removeUpdatedListener(listener)listenerFunction the function to remove- Returns Promise resolve to request or rejecting to error
addDeletedListener
Adds a listener for the subsystem's deleted event
addDeletedListener(listener)listenerFunction the function to execute ondeleted- Returns Promise resolving to request or rejecting to error
removeDeletedListener
Removes a listener for the subsystems deleted event
removeDeletedListener(listener)listenerFunction the function to remove- Returns Promise resolve to request or rejecting to error