db.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import hasha from 'hasha';
  2. function getLeafId(nodePath) {
  3. return hasha(nodePath.join('#'), { algorithm: 'sha256', encoding: 'hex' });
  4. }
  5. async function dbWrapper(client, dbName) {
  6. try {
  7. await client.db.get(dbName);
  8. } catch (e) {
  9. await client.db.create(dbName);
  10. }
  11. const db = await client.use(dbName);
  12. return {
  13. get: async function get(nodePath, callback) {
  14. const contentId = getLeafId(nodePath);
  15. db.get(contentId, (err, reply) => {
  16. if (err) {
  17. callback(null);
  18. } else {
  19. callback(reply);
  20. }
  21. });
  22. },
  23. set: async function set(nodePath, data, callback) {
  24. const contentId = getLeafId(nodePath);
  25. db.get(contentId, (getError, existingDoc) => {
  26. if (getError) {
  27. db.insert({ ...data, _id: contentId }, (insertNewError, reply) => {
  28. if (insertNewError) {
  29. throw new Error(insertNewError);
  30. } else if (callback) {
  31. callback(reply);
  32. }
  33. });
  34. } else {
  35. db.insert({ ...data, _id: contentId, _rev: existingDoc._rev }, (updateError, reply) => {
  36. if (updateError) {
  37. throw new Error(updateError);
  38. } else if (callback) {
  39. callback(reply);
  40. }
  41. });
  42. }
  43. });
  44. },
  45. };
  46. }
  47. export default dbWrapper;