npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-azure-cosmos

v2.4.0

Published

The Azure cosmos db for Nest framework (node.js)

Downloads

10

Readme

Description


This is forked from https://github.com/nestjs/azure-database and modified to work only with Azure Cosmos DB. The credit goes to the original author.

For Azure Cosmos DB support

  1. Create or update your existing .env file with the following content:
AZURE_COSMOS_DB_NAME=
AZURE_COSMOS_DB_ENDPOINT=
AZURE_COSMOS_DB_KEY=
  1. IMPORTANT: Make sure to add your .env file to your .gitignore! The .env file MUST NOT be versioned on Git.

  2. Make sure to include the following call to your main file:

if (process.env.NODE_ENV !== 'production') require('dotenv').config();

This line must be added before any other imports!

Example

Note: Check out the CosmosDB example project included in the sample folder

Prepare your entity

  1. Create a new feature module, eg. with the nest CLI:
$ nest generate module event
  1. Create a Data Transfer Object (DTO) inside a file named event.dto.ts:
export class EventDTO {
  name: string;
  type: string;
  date: Date;
  location: Point;
}
  1. Create a file called event.entity.ts and describe the entity model using the provided decorators:
  • @CosmosPartitionKey(value: string): Represents the PartitionKey of the entity (required).

  • @CosmosDateTime(value?: string): For DateTime values.

For instance, the shape of the following entity:

import { CosmosPartitionKey, CosmosDateTime, Point } from 'nestjs-azure-database';

@CosmosPartitionKey('type')
export class Event {
  id?: string;
  type: string;
  @CosmosDateTime() createdAt: Date;
  location: Point;
}

Will be automatically converted to:

{
  "type": "Meetup",
  "createdAt": "2019-11-15T17:05:25.427Z",
  "position": {
    "type": "Point",
    "coordinates": [2.3522, 48.8566]
  }
}
  1. Import the AzureCosmosDbModule inside your Nest feature module event.module.ts:
import { Module } from '@nestjs/common';
import { AzureCosmosDbModule } from 'nestjs-azure-database';
import { EventController } from './event.controller';
import { EventService } from './event.service';
import { Event } from './event.entity';

@Module({
  imports: [
    AzureCosmosDbModule.forRoot({
      dbName: process.env.AZURE_COSMOS_DB_NAME,
      endpoint: process.env.AZURE_COSMOS_DB_ENDPOINT,
      key: process.env.AZURE_COSMOS_DB_KEY,
    }),
    AzureCosmosDbModule.forFeature([{ dto: Event }]),
  ],
  providers: [EventService],
  controllers: [EventController],
})
export class EventModule {}

CRUD operations

  1. Create a service that will abstract the CRUD operations:
$ nest generate service event
  1. Use the @InjectModel(Event) to get an instance of the Azure Cosmos DB Container for the entity definition created earlier:
import { Injectable } from '@nestjs/common';
import { InjectModel } from 'nestjs-azure-database';
import { Event } from './event.entity';

@Injectable()
export class EventService {
  constructor(
    @InjectModel(Event)
    private readonly eventContainer,
  ) {}
}

The Azure Cosmos DB Container provides a couple of public APIs and Interfaces for managing various CRUD operations:

CREATE

create(entity: T): Promise<T>: creates a new entity.


  @Post()
  async create(event: Event): Promise<Event> {
      return this.eventContainer.items.create(event)
  }
READ

query<T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>: run a SQL Query to find a document.

  @Get(':id')
  async getContact(@Param('id') id) {
    try {
       const querySpec = {
           query: "SELECT * FROM root r WHERE r.id=@id",
           parameters: [
             {
               name: "@id",
               value: id
             }
           ]
         };
        const { resources } = await this.eventContainer.items.query<Event>(querySpec).fetchAll()
         return resources
    } catch (error) {
      // Entity not found
      throw new UnprocessableEntityException(error);
    }
  }
UPDATE

read<T>(options?: RequestOptions): Promise<ItemResponse<T>>: Get a document. replace<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>>: Updates a document.

  @Put(':id')
  async saveEvent(@Param('id') id, @Body() eventData: EventDTO) {
    try {
      const { resource: item } = await this.eventContainer.item<Event>(id, 'type').read()

      // Disclaimer: Assign only the properties you are expecting!
      Object.assign(item, eventData);

      const { resource: replaced } = await this.eventContainer
       .item(id, 'type')
       .replace<Event>(item)
      return replaced
    } catch (error) {
      throw new UnprocessableEntityException(error);
    }
  }
DELETE

delete<T>(options?: RequestOptions): Promise<ItemResponse<T>>: Removes an entity from the database.


  @Delete(':id')
  async deleteEvent(@Param('id') id) {
    try {
      const { resource: deleted } = await this.eventContainer
       .item(id, 'type')
       .delete<Event>()

      return deleted;
    } catch (error) {
      throw new UnprocessableEntityException(error);
    }
  }

Support

Nest is an MIT-licensed open source project.

License

Nest is MIT licensed.