Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Azure CosmosDB Database module for Nest framework (node.js) ☁️

License

NotificationsYou must be signed in to change notification settings

nestjs/azure-database

Repository files navigation

Nest Logo

A progressiveNode.js framework for building efficient and scalable server-side applications.

NPM VersionPackage LicenseNPM DownloadsCoverageDiscordBackers on Open CollectiveSponsors on Open Collective

Description

Azure Database (Table Storage,Cosmos DB - NoSQL) module forNest framework (node.js)

Disclaimer

You are reading the documentation for version 3. If you are looking for version 2 documentation,click here. Please also note that version 2 is no longer maintained and will not receive any updates!

Before Installation

For Cosmos DB (NoSQL ONLY)

  1. Create a Cosmos DB account and resource (read more)
  2. Note down the "URI", Database name and the "Primary Key" (or "Secondary Key") - You will need them later

For Table Storage

  1. Create a Storage account and resource (read more)
  2. Note down the "Connection string" - You will need it later

Installation

$ npm i --save @nestjs/azure-database

Usage

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 yourmain.ts 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 thesample 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 namedevent.dto.ts:
exportclassEventDTO{id?:string;name:string;type:string;createdAt:Date;}
  1. Create a file calledevent.entity.ts and describe the entity model using the provided decorators:
  • @CosmosPartitionKey(value: string | HierarchicalPartitionKey): Represents thePartitionKey orHierarchicalPartitionKey of the entity (required).

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

Important: Using a Hierarchical Partition Key requires a container that uses hierarchical partition keys,read more.

For instance, the shape of the following entity:

import{CosmosDateTime,CosmosPartitionKey}from'@nestjs/azure-database';import{PartitionKeyDefinitionVersion,PartitionKeyKind}from'@azure/cosmos';@CosmosPartitionKey({paths:['/name','/type/label'],version:PartitionKeyDefinitionVersion.V2,kind:PartitionKeyKind.MultiHash,})exportclassEvent{id?:string;name:string;type:{label:string;};  @CosmosDateTime()createdAt:Date;}

Will be automatically converted to:

{"name":"NestJS Meetup","type": {"label":"Meetup"  },"createdAt":"2019-11-15T17:05:25.427Z"}
  1. Import theAzureCosmosDbModule inside your Nest feature moduleevent.module.ts:
import{AzureCosmosDbModule}from'@nestjs/azure-database';import{Module}from'@nestjs/common';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,retryAttempts:1,}),AzureCosmosDbModule.forFeature([{dto:Event}]),],})exportclassEventModule{}

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 DBContainer for the entity definition created earlier:
import{InjectModel}from'@nestjs/azure-database';importtype{Container}from'@azure/cosmos';import{Injectable}from'@nestjs/common';import{Event}from'./event.entity';@Injectable()exportclassEventService{constructor(    @InjectModel(Event)privatereadonlyeventContainer:Container,){}}

@InjectModel(Event) will inject an Azure Cosmos DBContainer instance for theEvent entity. TheContainer provides a list of public methods for managing the database.

IMPORTANT: Please note that theContainer instance is not a NestJS repository. It is the actual instance provided by the officialAzure Cosmos DB SDK.

CREATE
asynccreate(eventDto:EventDTO):Promise<Event>{const{ resource}=awaitthis.eventContainer.items.create<Event>(eventDto,);returnresource;}
READ

Fetches all the results of the query.

asyncgetEvents():Promise<Event[]>{constquerySpec={query:'SELECT * FROM events',};const{ resources}=awaitthis.eventContainer.items.query<Event>(querySpec).fetchAll();returnresources;}

Fetch a single resource.

asyncgetEvent(id:string,partitionKey:string|string[]):Promise<Event>{const{ resource}=awaitthis.eventContainer.item(id,type).read<Event>();returnresource;}
UPDATE

Replaces an item in the database.

asyncupdateEvent(id:string,partitionKey:string|string[],eventData:EventDTO,):Promise<Event>{let{resource:item}=awaitthis.eventContainer.item(id,type).read<Event>();item={    ...item,    ...eventData,};const{resource:replaced}=awaitthis.eventContainer.item(id,type).replace(item);returnreplaced;}
DELETE

Deletes an item from the database.

asyncdeleteEvent(id:string,partitionKey:string|string[]):Promise<Event>{const{resource:deleted}=awaitthis.eventContainer.item(id,type).delete<Event>();returndeleted;}

Hierarchical Partition Keys

If using hierarchical partition keys, you need to provide the partition key as an array of strings when calling one of the CRUD methods on theContainer. For example, when reading a single resource:

this.eventContainer.item("1234",['foo','bar']).read<Event>();

Read more aboutHierarchical Partition Keys.

For Azure Table Storage support

  1. Create or update your existing.env file with the following content:
AZURE_STORAGE_CONNECTION_STRING=
  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 yourmain.ts file:

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

This line must be added before any other imports!

  1. TheAzureTableStorageModule will automatically read theAZURE_STORAGE_CONNECTION_STRING environment variable and use it to connect to your Azure Storage account.

Example

Check out the Table Storage example project included in thesample 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 namedevent.dto.ts:
exportclassEventDTO{name:string;type:string;}
  1. Create a file calledevent.entity.ts and describe the entity model using plain JavaScript objects.The only requirement is to provide apartitionKey and arowKey properties. For instance, the shape of the following entity:
exportclassEvent{partitionKey:string;// requiredrowKey:string;// requiredname:string;type:string;}
  1. Import theAzureTableStorageModule inside your Nest feature moduleevent.module.ts:
import{Module}from'@nestjs/common';import{AzureTableStorageModule}from'@nestjs/azure-database';@Module({imports:[AzureTableStorageModule.forFeature(Event)],})exportclassEventModule{}

You can optionally pass in the following arguments:

import{Module}from'@nestjs/common';import{AzureTableStorageModule}from'@nestjs/azure-database';@Module({imports:[AzureTableStorageModule.forFeature(Event,{table:'foobar',createTableIfNotExists:true,}),],})exportclassEventModule{}
  • table: string: The name of the table. If not provided, the name of theEvent entity will be used as a table name
  • createTableIfNotExists: boolean: Whether to automatically create the table if it doesn't exists or not:
    • Iftrue the table will be created during the startup of the app.
    • Iffalse the table will not be created.You will have to create the table by yourself before querying it!

CRUD operations

  1. Create a service that will abstract the CRUD operations:
$ nest generate service event
  1. Use the@InjectRepository(Event) to get an instance of the AzureRepository for the entity definition created earlier:
import{InjectRepository,Repository}from'@nestjs/azure-database';import{Injectable}from'@nestjs/common';import{Event}from'./event.entity';@Injectable()exportclassEventService{constructor(    @InjectRepository(Event)privatereadonlyeventRepository:Repository<Event>,){}}

TheAzureTableStorageRepository provides a list of public methods for managing various CRUD operations:

CREATE

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

asynccreate(event:Event):Promise<Event>{returnawaitthis.eventRepository.create(event);}
READ

find(partitionKey: string, rowKey: string): Promise<T>: finds one entity using itspartitionKey androwKey.

asyncfind(partitionKey:string,rowKey:string):Promise<Event>{returnawaitthis.eventRepository.find(partitionKey,rowKey);}

findAll(options: { queryOptions?: TableEntityQueryOptions }): Promise<T[]>: finds all entities.

asyncfindAll(options:{queryOptions?:TableEntityQueryOptions}):Promise<Event[]>{returnawaitthis.eventRepository.findAll();}
UPDATE

update(partitionKey: string, rowKey: string, entity: T): Promise<T>: Updates an entity using a "merge" strategy.

asyncupdate(partitionKey:string,rowKey:string,event:Event,):Promise<Event>{returnawaitthis.eventRepository.update(partitionKey,rowKey,event);}
DELETE

delete(partitionKey: string, rowKey: string): Promise<DeleteTableEntityResponse>: Removes an entity from the table.

asyncdelete(partitionKey:string,rowKey:string):Promise<void>{awaitthis.eventRepository.delete(partitionKey,rowKey);}

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, pleaseread more here.

Stay in touch

License

Nest isMIT licensed.

About

Azure CosmosDB Database module for Nest framework (node.js) ☁️

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors25


[8]ページ先頭

©2009-2025 Movatter.jp