2.4.0 • Published 7 months ago

nestjs-azure-cosmos v2.4.0

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

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.

2.3.2

7 months ago

2.4.0

7 months ago

2.3.1

1 year ago

2.3.0

1 year ago