Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. const CosmosClient = require("@azure/cosmos").CosmosClient;
  2. const config = require("../config");
  3.  
  4. class BaseDao {
  5. /**
  6. * Manages reading, adding, and updating Tasks in Cosmos DB
  7. * @param {string} collectionId
  8. */
  9. constructor(collectionId){
  10. this.client = config.cosmosClient;
  11. this.databaseId = config.databaseId;
  12. this.collectionId = collectionId;
  13.  
  14. this.database = null;
  15. this.container = null;
  16.  
  17. this.init(err => {
  18. console.error(err);
  19. })
  20. .catch(err => {
  21. console.error(err);
  22. console.error("Shutting down because there was an error setting up the database.");
  23. process.exit(1);
  24. });
  25. }
  26.  
  27. async init() {
  28. console.log("Setting up the database...");
  29. const dbResponse = await this.client.databases.createIfNotExists({
  30. id: this.databaseId
  31. });
  32. this.database = dbResponse.database;
  33. console.log("Setting up the database...done!");
  34. console.log("Setting up the container...");
  35. const coResponse = await this.database.containers.createIfNotExists({
  36. id: this.collectionId
  37. });
  38. this.container = coResponse.container;
  39. console.log("Setting up the container...done!");
  40. }
  41.  
  42. async find(querySpec) {
  43. console.log("Querying for items from the database");
  44. if (!this.container) {
  45. throw new Error("Collection is not initialized.");
  46. }
  47. const { result: results } = await this.container.items
  48. .query(querySpec)
  49. .toArray();
  50. return results;
  51. }
  52.  
  53. async addItem(item) {
  54. console.log("Adding an item to the database");
  55. const { body: doc } = await this.container.items.create(item);
  56. return doc;
  57. }
  58.  
  59. async updateItem(item) {
  60. console.log("Update an item in the database");
  61. const { body: replaced } = await this.container.item(item.id).replace(item);
  62. return replaced;
  63. }
  64.  
  65. async getItem(itemId) {
  66. const { body } = await this.container.item(itemId).read();
  67. return body;
  68. }
  69.  
  70. async getAllItems() {
  71. const { body } = await this.container.items.read();
  72. return body;
  73. }
  74.  
  75. }
  76.  
  77. module.exports = BaseDao;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement