Skip to content

Create REST API

Project Structure

Create new API Project

1
mio new api <api-name>

Example

1
mio new api DemoApi

Decorators

Routable

  1. @Routable('route-path')
  2. @Routable('route-path', pre:[])

Warning

Following format is depricated. Instead use method annotation like @Get(), @Post etc.

@Routable('route-path', 'verbe')

example

1
2
3
4
5
6
7
8
9
import { Routable } from 'mission.api';

@Routable('/health')
export class UserController {
    @Get()
    public static async getUsers(req: Request, res: Response, next: NextFunction): Promise<boolean> {
        return { ... };
    }
}

Controller

Warning

All public methods should be static async.

Access specifiers public would be exposed to public as REST service.

Example:

1
2
3
4
5
6
7
    @Routable('/user')
    export class UserRegistrationController {
        @Get()
        public static async getUsers(req: Request, res: Response, next: NextFunction): Promise<any> {
            ...
        }
    }

Action Result

Json Result (default)

File Download Result

Built-in Controllers

Health Check Controller

1
2
3
4
5
6
7
8
9
@Routable('/health', 'GET')
export class HealthService {
    public static async liveness(req: Request, res: Response, next: NextFunction): Promise<boolean> {
        return true;
    }
    public static async readiness(req: Request, res: Response, next: NextFunction): Promise<boolean> {
        return true;
    }
}
To Check the liveness of the appliation

1
http://localhost:3000/health/liveness

To Check the readiness of the application

1
http://localhost:3000/health/readiness

Note

Readiness api need to be override to check the readiness of the other resources like Sql / NoSql database, redis cache, etc.

Facade Controller

Environment Variables

All evironment variables configured in .env file in root folder. mission development environment allows you to keep multiple environment file in env folder like dev.env, prod.env, test.env and chose the file on demand by cli command.

Warning

Should not edit the .env file directly. instead edit the appropriate environment file available in the env folder.

Configuration

The application configurations available in the config folder.

Web Server Configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
interface WebServerConfig {
    apiPort: number;
    isHttpsEnabled: boolean;
    httpsCertificatepath: string;
    httpsKeypath: string;
    corsOptions: CorsOptions;
}

interface CorsOptions {
    origin?: boolean | string | RegExp | (string | RegExp)[] | CustomOrigin;
    methods?: string | string[];
    allowedHeaders?: string | string[];
    exposedHeaders?: string | string[];
    credentials?: boolean;
    maxAge?: number;
    preflightContinue?: boolean;
    optionsSuccessStatus?: number;
}

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { config, DotenvResult } from 'dotenv';
import { StaticFileConfig, WebServerConfig } from 'mission.api';

const env: DotenvResult = config();
if (env.error) {
    throw env.error;
}

export const WebConfig: WebServerConfig = {
    apiPort: Number(process.env.WEB_PORT),
    corsOptions: {  
        allowedHeaders: (process.env.CORS_ALLOWED_HEADERS || '').split(','),
        credentials: Boolean(process.env.CORS_CREDENTIALS),
        exposedHeaders: (process.env.CORS_EXPOSED_HEADERS || '').split(','),
        maxAge: Number(process.env.CORS_MAX_AGE),
        methods: (process.env.CORS_METHODS || '').split(','),
        origin: process.env.CORS_ORIGIN,
    },
    httpsCertificatepath: process.env.WEB_SSL_CERTIFICATE_PATH || '',
    httpsKeypath: process.env.WEB_SSL_KEY_PATH || '',
    isHttpsEnabled: !!process.env.WEB_SSL_CERTIFICATE_PATH,
};

export const FileConfig: StaticFileConfig = {
    dotfiles: 'ignore',
    etag: false,
    extensions: ['htm', 'html'],
    index: ['index.html', 'index.htm'],
    maxAge: process.env.STATIC_FILE_MAX_AGE || '1d',
    redirect: false,
    setHeaders: (res: any, path: string, stat: string) => {
        res.set('x-timestamp', Date.now().toString());
    },
};

Finally can create a WebServer instance with this config as follows.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { ApplicationRoutes, GetRouter, Router, WebServer } from 'mission.api';
import { WebConfig } from './config';

const server = new WebServer(WebConfig, console);

import './controller';
const route: Router = GetRouter();
route.use(ApplicationRoutes);

server.init();
server.addApiRouting('/', route);
server.start();

Logger Configuration Interface

1
2
3
4
5
6
interface LoggerInstance {
    log: Function;
    info: Function;
    warn: Function;
    error: Function;
}
Morgan Logger configuration:

Set the following evironment variable.

1
process.env.MORGAN = 'dev'

Accepted Values are:

  1. combined

  2. common

  3. dev (default)

  4. short

  5. tiny

More Reference

API Middlewares

Util

Wrap

wrap middleware is used to handle the promise response and ResultActions in generic.

1
Wrap((req:Request, res:Response, next:NextFunction)=>{});

ErrorWrap