Wondering what’s next for npm?Check out our public roadmap! »

    @nestjs-addons/in-memory-db
    TypeScript icon, indicating that this package has built-in type declarations

    3.0.3 • Public • Published

    NestJS Addons: In-Memory DB

    npm version npm downloads Commitizen friendly CI Status semantic-release All Contributors

    Breaking Changes

    Please note that starting with V2.0.0, the InMemoryDB* has been deprecated and moved to V1 instances. For more information on this API, checkout docs here: V1 Docs.

    Detailed Changes:

    • All V1 assets have been renamed to InMemoryDBv1***
    • New V2+ assets are the same name as before the V1 deprecation. You will just need to make modifications to support the id being a string as opposed to number
    • id has been changed from number to string to support GUIDs.
    • You can now optionally provide a getNextId function that the service will use to generate new string IDs. By default, it will use the uuid npm package and v4 implementation.

    Description

    @nestjs-addons/in-memory-db provides a ridiculously simple, no configuration needed, way to create a simple in-memory database for use in your nestjs applications. You simply define an interface that extends the interface InMemoryDBEntity, inject the InMemoryDBService<T> into your controllers and/or services, and immediately profit. The records are stored in-memory, as a singleton, for each interface, for the life of the service.

    This provides a great way to quickly get up and running with prototypes and mock backends.

    Table of Contents

    Installation

    Option 1

    With NPM

    $ npm i --save @nestjs-addons/in-memory-db

    With Yarn

    $ yarn add @nestjs-addons/in-memory-db

    Option 2

    The library support nest add command, you can run the below command to install and import the libary to root module.

    nest add @nestjs-addons/in-memory-db

    Video Walkthrough

    Quick Start

    Import into Module(s)

    To get started, let's first update our app.module.ts to include the necessary pieces.

    While we are importing to the AppModule in this example, InMemoryDBModule could be imported in Feature modules just as well.

    Registering a forRoot InMemoryDBModule

    // app.module.ts
    
    import { Module } from '@nestjs/common';
    import { InMemoryDBModule } from '@nestjs-addons/in-memory-db';
    ...
    
    @Module({
      ...
      imports: [InMemoryDBModule.forRoot({})],
      ...
    })
    export class AppModule {}

    As you can see we did the following:

    • Import InMemoryDBModule from @nestjs-addons/in-memory-db
    • Add InMemoryDBModule to the imports array in the @Module of your choice

    Define an interface for each InMemoryEntity

    An instance of InMemoryDBService<T> will be created for each InMemoryDBEntity entity interface defined. The InMemoryDBEntity adds an id: string property as the only required field. Additional fields can be defined by extending the interface.

    To define a new InMemoryDBEntity extension create an interface similar to the following example:

    interface UserEntity extends InMemoryDBEntity {
      firstName: string;
      lastName: string;
      emailAddress: string;
      admin: boolean;
    }

    Now we can make use of our new interface when injecting the InMemoryDBService<T> into our controllers or other services.

    Inject into Controller(s) and/or Services(s)

    In order to use the InMemoryDBService<T> we need to do the following:

    • Add private readonly inMemoryDB: InMemoryDBService<T> to the constructor of each controller and/or service that you would like to use it in.
    • Begin using InMemoryDBService as expected.

    An example of injecting InMemoryDBService into a UserController for the UserEntity we defined earlier would look something like this:

    @Controller()
    export class UserController {
      constructor(private readonly userService: InMemoryDBService<UserEntity>) {}
    
      @Get('users/:id')
      getUser(@Param() id: string): UserEntity {
        return this.userService.get(id);
      }
    
      @Post('users')
      createUser(@Body() user: UserEntity): UserEntity {
        return this.userService.create(user);
      }
    }

    Feature Modules - Registering Multiple Instances using forFeature

    Registering multiple instances for specific feature modules is super simple. Each feature module is guaranteed isolated to that feature. In order to get up and running you need to do the following:

    Registering a forFeature InMemoryDBService

    For each feature module(s), do the following:

    // feature-one.module.ts
    
    import { Module } from '@nestjs/common';
    import { InMemoryDBModule } from '@nestjs-addons/in-memory-db';
    ...
    
    @Module({
      ...
      imports: [InMemoryDBModule.forFeature('one', {})],
      ...
    })
    export class FeatureOneModule {}

    As you can see we:

    • Imported InMemoryDBModule from @nestjs-addons/in-memory-db
    • Added InMemoryDBModule to the imports array in the @Module of your choice
    • Added the forFeature method call passing one as the feature name

    Using the Feature Instance

    If you would like to use the feature-specific instance, make use of the included @InjectInMemoryDBService decorator:

    @Controller({...})
    export class FeatureOneController {
      constructor(@InjectInMemoryDBService('one') private oneService: InMemoryDBService<OneEntity>) {}
      ...
      @Get()
      getAll(): OneEntity[] {
        return this.oneService.getAll();
      }
    }

    Using this decorator ensures that the correct instance is injected.

    Entity Controller

    In order to prevent code duplication and boilerplate for each controller, we have created two base entity controllers InMemoryDBEntityController and InMemoryDBEntityAsyncController. This allows you to quickly provide endpoints to make requests without having to manually implement each action.

    To use the controllers, simply create a new controller and extend it with one of the provided base controllers.

    @Controller('api/users')
    class UsersController extends InMemoryDBEntityController<UserEntity> {
      constructor(protected dbService: InMemoryDBService<UserEntity>) {
        super(dbService);
      }
    }

    In order to have an Entity Controller use a feature-specific instance of the service, use the decorator InjectInMemoryDBService in the controller's provided by this library as shown below:

    @Controller('api/users')
    class UsersController extends InMemoryDBEntityController<UserEntity> {
      constructor(
        @InjectInMemoryDBService('customer')
        protected readonly inMemoryDBService: InMemoryDBService<UserEntity>,
      ) {
        super(inMemoryDBService);
      }
    }

    Docs

    Click here for more detailed API Documentation

    DEPRECATED V1 API - Click here for more detailed API Documentation

    Stay in touch

    Maintainers

    Wes Grimes
    Wes Grimes

    🚇 ⚠️ 💻
    Jay Bell
    Jay Bell

    ⚠️ 💻
    Dominik Pieper
    Dominik Pieper

    ⚠️ 💻

    Contributors

    Thanks goes to these wonderful people (emoji key):

    Chris Whited
    Chris Whited

    🚇 ⚠️ 💻
    Wes Copeland
    Wes Copeland

    💻 ⚠️
    Jordan
    Jordan

    💻 ⚠️
    Santosh Yadav
    Santosh Yadav

    💻 ⚠️
    Itay Oded
    Itay Oded

    💻 ⚠️

    This project follows the all-contributors specification. Contributions of any kind welcome!

    License

    NestJS Addons is MIT licensed.

    Install

    npm i @nestjs-addons/in-memory-db

    DownloadsWeekly Downloads

    221

    Version

    3.0.3

    License

    MIT

    Unpacked Size

    87.1 kB

    Total Files

    88

    Last publish

    Collaborators

    • avatar
    • avatar
    • avatar