@owlmeans/resource
v0.1.7
Published
Abstract CRUD interface and types for all data persistence in OwlMeans applications.
Readme
@owlmeans/resource
Abstract CRUD interface and types for all data persistence in OwlMeans applications.
Overview
Resource<T>interface:get,load,list,save,create,update,delete,pickResourceRecordbase type ({ id?: string }) that all stored records extendResourceMaker<R, T>factory signature used bymakeMongoResource,createStateResource, etc.ListResult<T>,ListOptions,ListPagerfor paginated queries- Error classes:
ResourceError,UnknownRecordError,RecordExists
Installation
bun add @owlmeans/resourceUsage
Define a resource maker following the standard factory pattern:
import type { ResourceMaker, ResourceRecord } from '@owlmeans/resource'
import { makeMongoResource } from '@owlmeans/mongo-resource'
interface ProjectRecord extends ResourceRecord {
entityId: string
alias: string
createdAt: Date
}
export const makeProjectResource: ResourceMaker<ProjectRecord> = (dbAlias, serviceAlias) => {
return makeMongoResource<ProjectRecord>('project', dbAlias, serviceAlias, makeProjectResource)
}Use resource methods in a handler:
import { UnknownRecordError } from '@owlmeans/resource'
import type { ListResult } from '@owlmeans/resource'
// Get or throw
const project = await ctx.project().get(projectId)
// Load (returns null if not found)
const story = await ctx.story().load(storyId)
// List with criteria and pagination
const result: ListResult<ProjectRecord> = await ctx.project().list({
criteria: { entityId: req.auth!.entityId },
pager: { page: 0, size: 20 }
})API
Resource<T> methods
get(id, field?, opts?)— fetch by ID; throwsUnknownRecordErrorif missingload(id, field?, opts?)— fetch by ID; returnsnullif missinglist(criteria?, opts?)— paginated list; returnsListResult<T>create(record, opts?)— insert; throwsRecordExistsif already existssave(record, opts?)— upsert by IDupdate(record, opts?)— update; throwsUnknownRecordErrorif missingdelete(id, opts?)— remove; returns the deleted record ornullpick(id, opts?)— likegetbut optimized for existence checks
ResourceMaker<R, T>
interface ResourceMaker<R extends ResourceRecord, T extends Resource<R> = Resource<R>> {
(dbAlias?: string, serviceAlias?: string): T
}Helpers
prepareListOptions(defPageSize, criteria?, opts?)— normalize list criteria + pagerfilterObject(obj, keep?)— strip null/undefined fields from a record before saving
Error Classes
ResourceError— base resource errorUnknownRecordError— record not found (has.idgetter)RecordExists— duplicate record oncreateMisshapedRecord— invalid record structure
Related Packages
@owlmeans/mongo-resource— MongoDB implementation@owlmeans/redis-resource— Redis implementation@owlmeans/state— in-memory implementation for client state
