# tenant-core

> Nestjs module for multitenant support

Latest version **0.0.3** (published 2020-12-08) · MIT license · 0 weekly downloads

## Install

```sh
npm install tenant-core
pnpm add tenant-core
yarn add tenant-core
bun add tenant-core
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.3 |
| Published | 2020-12-08 |
| First published | 2020-12-08 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 38.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | codegyn |
| Maintainers | duduzera1997, danilofelipe2607 |

## Links

- npm: https://www.npmjs.com/package/tenant-core
- Repository: https://github.com/Code-GYN/tenant-core
- npm.io page: https://npm.io/package/tenant-core

## Recent versions

- 0.0.3 (latest) — 2020-12-08
- 0.0.2 — 2020-12-08
- 0.0.1 — 2020-12-08

## README

<h1 align="center">tenant-core</h1>

<p align="center">
  A project to use multitenant for NestJs and Mongoose in Code-GYN
</p>

## Description
Core of multitenant for the Code-GYN.

## Installation

```bash
$ npm i --save @codegyn/tenant-core
```
OR
```bash
$ yarn add @codegyn/tenant-core
```

## Basic usage

**app.module.ts**

```typescript
import { Module } from "@nestjs/common";
import { TenantModule } from "@codegyn/tenant-core";
import { AnyModule } from "./any.module.ts";

@Module({
  imports: [
    TenantModule.forRoot({
        tenantIdentifier: 'X-TENANT-ID',
        options: () => {},
        uri: (tenantId: string) => `mongodb://localhost/test-tenant-${tenantId}`,
    }),
    AnyModule,
  ],
})
export class AppModule {}
```

Create class that describes your schema

**any.model.ts**

```typescript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Any extends Document {
    @Prop()
    name: string;

    @Prop()
    age: number;

}

export const AnySchema = SchemaFactory.createForClass(Any);
```

Inject Any for `AnyModule`

**any.module.ts**

```typescript
import { Module } from '@nestjs/common';
import { TenantModule } from '@codegyn/tenant-core';
import { AnyController } from './any.controller';
import { AnyService } from './any.service';
import { Any, AnySchema } from './schemas/any.schema';

@Module({
    imports: [
        TenantModule.forFeature([{ name: Any.name, schema: AnySchema }])
    ],
    controllers: [AnyController],
    providers: [AnyService],
})
export class AnyModule { }
```

Get the any model in a service

**any.service.ts**

```typescript
import { Injectable } from '@nestjs/common';
import { InjectTenantModel } from '@codegyn/tenant-core';
import { Model } from 'mongoose';
import { CreateAnyDto } from './dto/create-any.dto';
import { Any } from './schemas/any.schema';

@Injectable()
export class AnyService {
    constructor(
        @InjectTenantModel(Any.name) private readonly anyModel: Model<Any>
    ) { }

    async create(createAnyDto: CreateAnyDto): Promise<Any> {
        const createdAny = new this.anyModel(createAnyDto);
        return createdAny.save();
    }

    async findAll(): Promise<Any[]> {
        return this.anyModel.find().exec();
    }
}
```

Finally, use the service in a controller!

**any.controller.ts**

```typescript

import { Body, Controller, Get, Post } from '@nestjs/common';
import { AnyService } from './any.service';
import { CreateAnyDto } from './dto/create-any.dto';
import { Any } from './schemas/any.schema';

@Controller('any')
export class AnyController {
    constructor(private readonly anyService: AnyService) { }

    @Post()
    async create(@Body() createAnyDto: CreateAnyDto) {
        return this.anyService.create(createAnyDto);
    }

    @Get()
    async findAll(): Promise<Any[]> {
        return this.anyService.findAll();
    }
}
```

## Adding custom validators for the tenant

Let's say you want to handle a validation check to see if your tenant is registered. You can do 
this by implementing the `TenantValidator` interface and writing your own validation logic inside
the `validate` method. The library invokes this method internally.

### Note
Here we assume that `X-TENANT-ID` is passed in the request header so that its available for the validator.

**custom-tenant.validator.ts**

```typescript
import { TenantValidator } from '@app/tenant';
import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ITenantModel } from '../../core/models/tenant.model';

@Injectable()
export class CustomTenantValidator implements TenantValidator {
    private _tenantId: string;

    // This`Tenant` model definition schema is mapped to the common database and
    // not into the tenant database.
    constructor(@InjectModel('Tenant') private tenantModel: Model<ITenantModel>) { }

    /**
     * Method to set the tenant id
     *
     * @param {string} tenantId
     * @returns
     * @memberof CustomTenantValidator
     */
    setTenantId(tenantId: string): TenantValidator {
        this._tenantId = tenantId;
        return this; // Make sure to return the instance of the class back here.
    }

    /**
     * Your Custom Validation to verify if tenant exist in the common database
     *
     * Note: This method will be invoked by the library internally when
     * tenant id is present in the context.
     *
     * @returns {Promise<void>}
     * @memberof CustomTenantValidator
     */
    async validate(): Promise<void> {
        const exist = await this.tenantModel.exists({ name: this._tenantId });
        if (!exist) {
            throw new NotFoundException(`Tenant not found`);
        }
    }
}
```

Export the validator from your tenant module

**tenant.module.ts**

```typescript
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TenantSchema } from '../core/schemas/tenant.schema';
import { TenantController } from './tenant.controller';
import { TenantService } from './tenant.service';
import { CustomTenantValidator } from './validators/custom-tenant.validator';

@Module({
  imports: [
    // Here the connection represents the common database
    MongooseModule.forFeature([{ name: 'Tenant', schema: TenantSchema }])
  ],
  controllers: [TenantController],
  providers: [
    TenantService,
    // Your custom validator
    CustomTenantValidator,
  ],
  exports: [
    TenantService,
    CustomTenantValidator,
  ]
})
export class TenantModule {}
```

Export the database configuration

**config.ts**

```
export default () => ({
    database: {
        uri: process.env.MONGO_URI
    }
});
```

Finally you will also need to modify the module configuration.

**app.module.ts**

```typescript
import { Module } from "@nestjs/common";
import { TenantModule } from "@codegyn/tenant-core";
import { AnyModule } from "./any.module.ts";
import { ConfigModule, ConfigService } from '@nestjs/config';
import configuration from './config';
import { TenantModule } from './tenant/tenant.module';
import { CustomTenantValidator } from './tenant/validators/custom-tenant.validator';

@Module({
  imports: [
    // Load the default configuration file
    ConfigModule.forRoot({
      isGlobal: true,
      load: configuration,
    }),
    // Mongoose default connection
    MongooseModule.forRootAsync({
      useFactory: async (cfs: ConfigService) => cfs.get('database'),
      inject: [ConfigService],
    }),
    // Tenant async configuration
    TenantModule.forRootAsync({
      imports: [TenantModule],
      useFactory: async (cfs: ConfigService, tVal: CustomTenantValidator) => {
        return {
          // Base tenant configurations
          tenantIdentifier: 'X-TENANT-ID',
          options: () => {},
          uri: (tenantId: string) => `mongodb://localhost/test-tenant-${tenantId}`,
          // Custom validator to check if the tenant exist in common database
          validator: (tenantId: string) => tVal.setTenantId(tenantId),
        }
      },
      inject: [ConfigService, CustomTenantValidator],
    }),
    AnyModule,
  ],
})
export class AppModule {}
```

## Subdomain support

This library also enables the extraction of tenant id from the sudomain of the url.
For enabling this you need to modify your configuration like below.

**app.module.ts**

```typescript
import { Module } from "@nestjs/common";
import { TenantModule } from "@codegyn/tenant-core";
import { AnyModule } from "./any.module.ts";

@Module({
  imports: [
    TenantModule.forRoot({
        // This will allow the library to extract the subdomain as tenant id
        isTenantFromSubdomain: true,
        options: () => {},
        uri: (tenantId: string) => `mongodb://localhost/test-tenant-${tenantId}`,
    }),
    AnyModule,
  ],
})
export class AppModule {}
```

## Support for Mongo Transactions

There are cases when using Mongo Transactions we wouldn't get the flexibility of
mongoose to automatically initialize the empty collection for us. In that case
we can make use of the property in `TenantModuleOptions` which is `forceCreateCollections: true`
(set to false by default) to automatically initialize all collections that are mapped to `TenantModule`.

## Requirements

1.  @nest/mongoose +6.4.0
2.  @nestjs/common +6.10.1
3.  @nestjs/core +6.10.1
4.  mongoose (with typings `@types/mongoose`) +5.7.12

## Test

```bash
# e2e tests
$ npm run test:e2e
```

---
_Source: https://npm.io/package/tenant-core · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
