0.0.2 • Published 3 years ago
pouchdb-transform v0.0.2
PouchDB Advanced Transform Library
Apply a transform function to documents before and after they are stored in the database. These functions are triggered invisibly for every get(), put(), post(), bulkDocs(), allDocs(), changes() before or after, and also to documents added via replication.
This allows you to:
- Encrypt and decrypt sensitive document fields
- Compress and uncompress large content (e.g. to avoid hitting browser storage limits)
- Remove or modify documents before storage (e.g. to massage data from CouchDB)
Note: This plugin is modified from transform-pouch to enhance it's ability:
- add the
afterIncomingandbeforeOutgoinghook.incomingis triggered before saving to database.- returns must be an object with
docattribute.- can pass through extra options in the object to next hook.
- returns must be an object with
afterIncomingis triggered after saving.beforeOutgoingis triggered before getting from database.outgoingis triggered after getting from database.
Note: This API has not been stable yet. beforeOutgoing has not applied to all methods.
Usage
npm install pouchdb-transformAnd then attach it to the PouchDB object:
import PouchDB from 'pouchdb'
import transformPlugin from 'pouchdb-transform';
PouchDB.plugin(transformPlugin)API
When you create a new PouchDB, you need to configure the transform functions:
var pouch = new PouchDB('mydb');
pouch.transform({
async incoming(doc, args: IPouchDBWrapperArgs, type: TransformPouchType): ITransformIncomingResult {
// do something to the document before storage
return {doc, ...};
},
afterIncoming(result: ITransformIncomingResult, type: TransformPouchType): void {
if (result.ok) {
// do something to the successful document after storage
} else {
// the failed document to save.
}
},
beforeOutgoing(docId: any, args: IPouchDBWrapperArgs, type: TransformPouchType): BeforeOutgoingReturn {
// do something to the document before retrieval
// it will skip retrieval and use it as doc if returns
return this.fCache.get(docId);
},
async outgoing(doc: IDoc,
args: IPouchDBWrapperArgs,
type: TransformPouchType): IDoc {
// do something to the document after retrieval
return doc;
}
});Notes:
- You can provide an
incomingfunction, anoutgoingfunction, or both. - Your transform function must return the document itself, or a new document (or a promise for such).
incomingfunctions apply toput(),post(),bulkDocs(), and incoming replications.outgoingfunctions apply toget(),allDocs(),changes(),query(), and outgoing replications.- The
incoming/outgoingmethods can be async or sync – just return a Promise for a doc, or the doc itself.