| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- import hasha from 'hasha';
- function getLeafId(nodePath) {
- return hasha(nodePath.join('#'), { algorithm: 'sha256', encoding: 'hex' });
- }
- async function dbWrapper(client, dbName) {
- try {
- await client.db.get(dbName);
- } catch (e) {
- await client.db.create(dbName);
- }
- const db = await client.use(dbName);
- return {
- get: async function get(nodePath, callback) {
- const contentId = getLeafId(nodePath);
- db.get(contentId, (err, reply) => {
- if (err) {
- callback(null);
- } else {
- callback(reply);
- }
- });
- },
- set: async function set(nodePath, data, callback) {
- const contentId = getLeafId(nodePath);
- db.get(contentId, (getError, existingDoc) => {
- if (getError) {
- db.insert({ ...data, _id: contentId }, (insertNewError, reply) => {
- if (insertNewError) {
- throw new Error(insertNewError);
- } else if (callback) {
- callback(reply);
- }
- });
- } else {
- db.insert({ ...data, _id: contentId, _rev: existingDoc._rev }, (updateError, reply) => {
- if (updateError) {
- throw new Error(updateError);
- } else if (callback) {
- callback(reply);
- }
- });
- }
- });
- },
- };
- }
- export default dbWrapper;
|