Custom controllers

Describes how to create controllers using NestJS and manipulate data with PouchDB

From time to time you probably want to add some special behaviour to your mocks like filtering a list of resources, apply pagination, upload or download some files and so on. Mockly provides you a simple way to do it using NestJS.

Before all, you should be aware that we are using NestJS under the hood to create the server that exposes all your mocked resources. We've taking advantage of some of the awesome features provided by this library like controllers, interceptors or middlewares to build the tool and all the versatility it has to offer.

Creating a controller

If you're familiar with NestJS there is nothing new here. Otherwise, we recommend you to give a quick read to the controllers documentation to be up to date and ready to start.

When Mockly starts it looks in the current working directory for files with this pattern: *.custom-controller.ts. It's supposed that this files holds at least one NestJS's controller, and as a recommendation, we pray you to keep it this way. As you can imagine, this files contains something like that:

artists.custom-controller.ts
@Controller('artists')
export class ArtistCustomController {

    @Get()
    search (@Query('q') query: string) {
        // TODO Implement method logic...
    }
    
}

Manipulating data

Mockly uses PouchDB, an in-memory CouchDB-like database, to store your resources and data and kept all the manipulations you do to them in a session. When you're creating a custom controller you'll be able to get the database for your resource and control it as you desire. You can also use the built-in query system or the find API to create powerful queries to filter, sort or paginate your collections.

To get the database you need to inject the DatabaseRegistry service in your controller and then take the database you're interested in:

import { DatabaseRegistry } from '@mockly/server';

@Controller('artists')
export class ArtistsCustomController {
    private readonly database: PouchDB.Database;
    
    constructor (readonly registry: DatabaseRegistry) {
        this.database = registry.get('artists');
    }
}

Last updated