This normalized cache provides the following functionality:
- Data (de)normalization
- Data subscriptions
- Data validation
- Data invalidation
- Data expiration
- Computed fields
- Optimistic updates
- Garbage collection
The library is around 6 KB gzipped when using all features.
Installation:
npm install --save normalized-cacheimport{Cache,schema}from"normalized-cache";constAuthor=schema.object({name: "Author",});constPost=schema.object({name: "Post",fields: {author: Author,},});constcache=newCache({types: [Post],});cache.write({type: "Post",data: {id: "1",title: "Title",author: {id: "2",name: "Name",},},});constresult=cache.read({type: "Post",id: "1",});console.log(result.data);// {// id: "1",// title: "Title",// author: {// id: "2",// name: "Name",// },// }constresult2=cache.read({type: "Author",id: "2",});console.log(result2.data);// {// id: "2",// name: "Name",// }constresult3=cache.read({type: "Post",id: "1",select: cql`{ title author { name } }`,});console.log(result3.data);// {// title: "Title",// author: {// name: "Name",// },// }classCache{constructor(config?: CacheConfig): Cache;get(entityID: string,optimistic?: boolean): Entity|undefined;set(entityID: string,entity: Entity|undefined,optimistic?: boolean): Entity;identify(options: IdentifyOptions): string|undefined;read(options: ReadOptions): ReadResult|undefined;write(options: WriteOptions): WriteResult;delete(options: DeleteOptions): DeleteResult|undefined;invalidate(options: InvalidateOptions): InvalidateResult|undefined;watch(options: WatchOptions): Unsubscribable;silent(fn: ()=>void): void;transaction(fn: ()=>void): void;extract(optimistic?: boolean): SerializedData;restore(data: SerializedData): void;reset(): void;gc(): void;retain(entityID: string): Disposable;addOptimisticUpdate(updateFn: OptimisticUpdateFn): OptimisticUpdateDisposable;removeOptimisticUpdate(id: number): void;}interfaceCacheConfig{types?: ValueType[];onlyReadKnownFields?: boolean;onlyWriteKnownFields?: boolean;}constschema={array(config?: ArrayTypeConfig|ValueType): ArrayTypeboolean(config?: BooleanTypeConfig): BooleanTypenonNullable(config: NonNullableTypeConfig|ValueType): NonNullableTypenumber(config?: NumberTypeConfig): NumberTypeobject(config?: ObjectTypeConfig): ObjectTypestring(config?: StringTypeConfig|string): StringTypeunion(config: UnionTypeConfig|ValueType[]): UnionType}Schema types allow you to define entities, relationships and fields.
Learn more about the type system here.
When writing to the cache, a type must be provided.
cache.write({type: "Post",data: {id: "1",title: "Title"},});A ID can be specified if this cannot be inferred from the data itself:
cache.write({type: "Post",id: "1",data: {title: "Title"},});If the ID is an object or array it will be automatically serialized to a stable string:
cache.write({type: "Posts",id: {page: 1,limit: 10},data: [],});Reading from the cache can be done with the read method.
When no selector is given, all data related to the entity will be returned:
cache.write({type: "Author",data: {id: "2",name: "Name",},});cache.write({type: "Post",data: {id: "1",title: "Title",author: {id: "2",},},});constresult=cache.read({type: "Post",id: "1",});console.log(result.data);// {// id: "1",// title: "Title",// author: {// id: "2",// name: "Name",// },// }The resulting data can contain circular references when entities refer to each other.
Selectors can be used to select specific fields:
import{cql}from"normalized-cache";cache.write({type: "Author",data: {id: "2",name: "Name",},});cache.write({type: "Post",data: {id: "1",title: "Title",author: {id: "2",},},});constresult=cache.read({type: "Post",id: "1",select: cql`{ title author { name } }`,});console.log(result.data);// {// title: "Title",// author: {// name: "Name",// },// }Learn more about selectors here.
The write method also returns a selector that matches the exact shape of the input:
cache.write({type: "Author",data: {id: "2",name: "Name",},});const{ selector }=cache.write({type: "Post",data: {id: "1",title: "Title",author: {id: "2",},},});constresult=cache.read({type: "Post",id: "1",select: selector,});console.log(result.data);// {// id: "1",// title: "Title",// author: {// id: "2",// },// }Computed fields can be created by defining a field with a read function.
Defining a computed field for calculations:
constCart=schema.object({name: "Cart",fields: {totalPrice: {read: (cart)=>{returncart.items.reduce((total,item)=>total+item.price,0);},},},});Defining a relational field based on another field:
constAuthor=schema.object({name: "Author",});constPost=schema.object({name: "Post",fields: {author: {read: (post,{ toReference })=>{returntoReference({type: "Author",id: post.authorId});},},},});Fields that do not match with the schema will be reported in the invalidFields array:
constLoggedIn=schema.boolean({name: "LoggedIn",});constcache=newCache({types: [LoggedIn],});cache.write({type: "LoggedIn",data: "string",});constresult=cache.read({type: "LoggedIn",});if(result.invalidFields){console.log("Invalid data");}Fields that are missing will be reported in the missingFields array:
constLoggedIn=schema.boolean({name: "LoggedIn",});constcache=newCache({types: [LoggedIn],});constresult=cache.read({type: "LoggedIn",});if(result.missingFields){console.log("Missing data");}The stale flag indicates if some entity or field has been invalidated or if any expiresAt has past:
constLoggedIn=schema.boolean({name: "LoggedIn",});constcache=newCache({types: [LoggedIn],});cache.write({type: "LoggedIn",data: true,expiresAt: 0,});constresult=cache.read({type: "LoggedIn",});if(result.stale){console.log("Stale data");}Data in the cache can be watched with the watch method.
Watching for any change in a specific post and all related data:
const{ unsubscribe }=cache.watch({type: "Post",id: "1",callback: (result,prevResult)=>{// log},});unsubscribe();Watching specific fields:
cache.watch({type: "Post",id: "1",select: cql`{ title }`,callback: (result,prevResult)=>{if(!prevResult.stale&&result.stale){// The title became stale}},});Entities and fields can be invalidated with the invalidate method.
When an entity or field is invalidated, all related watchers will be notified.
Invalidate an entity:
cache.invalidate({type: "Post",id: "1",});Invalidate entity fields:
cache.invalidate({type: "Post",id: "1",select: cql`{ comments }`,});when expiresAt is specified, all affected fields will be considered stale after the given time:
cache.write({type: "Post",data: {id: "1"},expiresAt: Date.now()+60*1000,});Set expiration for certain types:
cache.write({type: "Post",data: {id: "1"},expiresAt: {Comment: Date.now()+60*1000,},});Entities and fields can be deleted with the delete method.
Deleting an entity:
cache.delete({type: "Post",id: "1",});Deleting specific fields:
cache.delete({type: "Post",id: "1",select: cql`{ title }`,});An optimistic update function can be used to update the cache optimistically.
These functions will be executed everytime the cache is updated, until they are removed.
This means that if new data is written to the cache, the optimistic update will be re-applied / rebased on top of the new data.
asyncfunctionaddComment(postID,text){functionaddCommentToPost(comment){constresult=cache.read({type: "Post",id: postID,select: cql`{ comments }`,});cache.write({type: "Post",id: postID,data: {comments: [...result.data.comments,comment]},});}constupdate=cache.addOptimisticUpdate(()=>{addCommentToPost({id: uuid(), text });});constcomment=awaitapi.addComment(postID,text);cache.transaction(()=>{update.dispose();addCommentToPost(comment);});}By default entities are shallowly merged and non-entity values are replaced.
This behavior can be customized by defining custom write functions on entities and fields.
Replacing entities instead of merging:
constAuthor=schema.object({name: "Author",write: (incoming)=>{returnincoming;},});Merging objects instead of replacing:
constPost=schema.object({name: "Post",fields: {content: {type: schema.object(),write: (incoming,existing)=>{return{ ...existing, ...incoming};},},},});Transforming values when writing:
constPost=schema.object({name: "Post",fields: {title: {write: (incoming)=>{if(typeofincoming==="string"){returnincoming.toUpperCase();}},},},});Multiple changes can be wrapped in a transaction to make sure watchers are only notified once after the last change:
cache.transaction(()=>{cache.write({type: "Post",data: {id: "1",title: "1"},});cache.write({type: "Post",data: {id: "2",title: "2"},});});Wrap changes with silent to prevent watchers from being notified:
cache.silent(()=>{cache.write({type: "Post",data: {id: "1",title: "1"},});});The gc method can be used to remove all unwatched and unreachable entities from the cache.
Use the retain method to prevent an entity from being removed.