Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const CosmosClient = require("@azure/cosmos").CosmosClient;
- const config = require("../config");
- class BaseDao {
- /**
- * Manages reading, adding, and updating Tasks in Cosmos DB
- * @param {string} collectionId
- */
- constructor(collectionId){
- this.client = config.cosmosClient;
- this.databaseId = config.databaseId;
- this.collectionId = collectionId;
- this.database = null;
- this.container = null;
- this.init(err => {
- console.error(err);
- })
- .catch(err => {
- console.error(err);
- console.error("Shutting down because there was an error setting up the database.");
- process.exit(1);
- });
- }
- async init() {
- console.log("Setting up the database...");
- const dbResponse = await this.client.databases.createIfNotExists({
- id: this.databaseId
- });
- this.database = dbResponse.database;
- console.log("Setting up the database...done!");
- console.log("Setting up the container...");
- const coResponse = await this.database.containers.createIfNotExists({
- id: this.collectionId
- });
- this.container = coResponse.container;
- console.log("Setting up the container...done!");
- }
- async find(querySpec) {
- console.log("Querying for items from the database");
- if (!this.container) {
- throw new Error("Collection is not initialized.");
- }
- const { result: results } = await this.container.items
- .query(querySpec)
- .toArray();
- return results;
- }
- async addItem(item) {
- console.log("Adding an item to the database");
- const { body: doc } = await this.container.items.create(item);
- return doc;
- }
- async updateItem(item) {
- console.log("Update an item in the database");
- const { body: replaced } = await this.container.item(item.id).replace(item);
- return replaced;
- }
- async getItem(itemId) {
- const { body } = await this.container.item(itemId).read();
- return body;
- }
- async getAllItems() {
- const { body } = await this.container.items.read();
- return body;
- }
- }
- module.exports = BaseDao;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement