Code Monkey home page Code Monkey logo

nestjs-dynamoose's Introduction

Nest Logo

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

NPM Version Package License NPM Downloads CI

Description

Dynamoose module for Nest.

Installation

$ npm install --save nestjs-dynamoose dynamoose

Example Project

A AWS NestJS Starter project has been created to demo the usage of this library.

Quick Start

1. Add import into your app module

src/app.module.ts

import { DynamooseModule } from 'nestjs-dynamoose';
import { UserModule } from './user/user.module';

@Module({
 imports: [
   DynamooseModule.forRoot(),
   UserModule,
 ],
})
export class AppModule {

forRoot() optionally accepts the following options defined by DynamooseModuleOptions:

interface DynamooseModuleOptions {
  aws?: {
    accessKeyId?: string;
    secretAccessKey?: string;
    region?: string;
  };
  local?: boolean | string;
  model?: ModelOptionsOptional;
  logger?: boolean | LoggerService;
}

There is also forRootAsync(options: DynamooseModuleAsyncOptions) if you want to use a factory with dependency injection.

2. Create a schema

src/user/user.schema.ts

import { Schema } from 'dynamoose';

export const UserSchema = new Schema({
  id: {
    type: String,
    hashKey: true,
  },
  name: {
    type: String,
  },
  email: {
    type: String,
  },
});

src/user/user.interface.ts

export interface UserKey {
  id: string;
}

export interface User extends UserKey {
  name: string;
  email?: string;
}

UserKey holds the hashKey/partition key and (optionally) the rangeKey/sort key. User holds all attributes of the document/item. When creating this two interfaces and using when injecting your model you will have typechecking when using operations like Model.update().

3. Add the models you want to inject to your modules

This can be a feature module (as shown below) or within the root AppModule next to DynamooseModule.forRoot().

src/user/user.module.ts

import { DynamooseModule } from 'nestjs-dynamoose';
import { UserSchema } from './user.schema';
import { UserService } from './user.service';

@Module({
  imports: [
    DynamooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
  ],
  providers: [
    UserService,
    ...
  ],
})
export class UserModule {}

There is also forFeatureAsync(factories?: AsyncModelFactory[]) if you want to use a factory with dependency injection.

4. Inject and use your model

src/user/user.service.ts

import { Injectable } from '@nestjs/common';
import { InjectModel, Model } from 'nestjs-dynamoose';
import { User, UserKey } from './user.interface';

@Injectable()
export class UserService {
  constructor(
    @InjectModel('User')
    private userModel: Model<User, UserKey>,
  ) {}

  create(user: User) {
    return this.userModel.create(user);
  }

  update(key: UserKey, user: Partial<User>) {
    return this.userModel.update(key, user);
  }

  findOne(key: UserKey) {
    return this.userModel.get(key);
  }

  findAll() {
    return this.userModel.scan().exec();
  }
}

Additional Example

1. Transaction Support

Both User and Account model objects will commit in same transaction.

import { Injectable } from '@nestjs/common';
import { InjectModel, Model, TransactionSupport } from 'nestjs-dynamoose';
import { User, UserKey } from './user.interface';
import { Account, AccountKey } from './account.interface';

@Injectable()
export class UserService extends TransactionSupport {
  constructor(
    @InjectModel('User')
    private userModel: Model<User, UserKey>,
    @InjectModel('Account')
    private accountModel: Model<Account, AccountKey>,
  ) {
    super();
  }

  async create(user: User, account: Account) {
    await this.transaction([
      this.userModel.transaction.create(user),
      this.accountModel.transaction.create(account),
    ]);
  }
}

2. Serializers Support

Define the additional serializers under DynamooseModule.forFeature().

@Module({
  imports: [
    DynamooseModule.forFeature([
      {
        name: 'User',
        schema: UserSchema,
        serializers: {
          frontend: { exclude: ['status'] },
        },
      },
    ]),
  ],
  ...
})
export class UserModule {}

Call the serialize function to exclude the status field.

@Injectable()
export class UserService {
  ...
  async create(user: User) {
    const createdUser = await this.userModel.create(user);
    return createdUser.serialize('frontend');
  }
  ...
}

License

Dynamoose module for Nest is MIT licensed.

nestjs-dynamoose's People

Contributors

renovate-bot avatar hardyscc avatar mickl avatar dependabot[bot] avatar andrewda avatar renovate[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.