Class API<Schema, ExtensionFn>


Type Parameters

Constructors

Properties

app: Application = ...
client: Client = ...
config: APIConfig = DEFAULT_CONFIG
extensionFn: ExtensionFn
schema: Schema

Methods

  • Parameters

    • handler: ((client: Client) => JsonMiddleware)
        • (client): JsonMiddleware
        • Parameters

          • client: Client

          Returns JsonMiddleware

    Returns void

     type Return = (
    // Return a status code and a function that will be called with the body of the response
    [statusCode: number, bodyFunction: (body: any) => any] |
    // Return a function that will be called with the body of the response
    (body: any) => any
    )

    Add a middleware to the API that will help authorize requests

     api.auth(client => async (req, res, next) => {
    const unauthorized = () => [401, () => ({error: 'Unauthorized'})];
    const isOp = api.createOpChecker(req);
    const token = req.headers['authorization'];
    const {path} = api.describeRequest(req)
    // Do not use a users email as your auth token, just an example
    const user: Schema['users'] = await client.query('select * from users where email = $1', [token]).then(({rows}) => rows[0]);
    if (!user) return unauthorized();
    if (isOp('users/:id', 'GET')) {
    if (user.id.toString() !== path.split('/').pop())
    return unauthorized();
    }
    });
  • Parameters

    Returns void

    Configure the API

    api.configure({port: 3001});
    
  • Parameters

    • req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>

    Returns ((route: (keyof Schema extends string
        ? keyof ReturnType<ExtensionFn> | string & keyof Schema | `${string & keyof Schema}/:id`
        : never) | (keyof Schema extends string
        ? keyof ReturnType<ExtensionFn> | string & keyof Schema | `${string & keyof Schema}/:id`
        : never)[], method?:
        | undefined
        | "GET"
        | "HEAD"
        | "POST"
        | "PUT"
        | "DELETE"
        | "CONNECT"
        | "OPTIONS"
        | "TRACE"
        | "PATCH"
        | (
            | "GET"
            | "HEAD"
            | "POST"
            | "PUT"
            | "DELETE"
            | "CONNECT"
            | "OPTIONS"
            | "TRACE"
            | "PATCH")[]) => boolean)

      • (route, method?): boolean
      • Parameters

        • route: (keyof Schema extends string
              ? keyof ReturnType<ExtensionFn> | string & keyof Schema | `${string & keyof Schema}/:id`
              : never) | (keyof Schema extends string
              ? keyof ReturnType<ExtensionFn> | string & keyof Schema | `${string & keyof Schema}/:id`
              : never)[]
        • method:
              | undefined
              | "GET"
              | "HEAD"
              | "POST"
              | "PUT"
              | "DELETE"
              | "CONNECT"
              | "OPTIONS"
              | "TRACE"
              | "PATCH"
              | (
                  | "GET"
                  | "HEAD"
                  | "POST"
                  | "PUT"
                  | "DELETE"
                  | "CONNECT"
                  | "OPTIONS"
                  | "TRACE"
                  | "PATCH")[] = ...

        Returns boolean

    • Create a function that checks if the request matches the route and method.
    • Useful for middleware.
    const isOp = api.createOpChecker(req);

    if (isOp('users/:id', 'GET')) {
    // Do something
    }
  • Parameters

    • req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>

    Returns {
        method: string;
        path: string;
        route: undefined | string;
    }

    • method: string
    • path: string
    • route: undefined | string

    Describe the operation of a request

    const {path, method} =api.describeReqOp(req);
    
  • Parameters

    • path: string
    • method:
          | "GET"
          | "HEAD"
          | "POST"
          | "PUT"
          | "DELETE"
          | "CONNECT"
          | "OPTIONS"
          | "TRACE"
          | "PATCH"

    Returns any

    Check if the API has a route

    api.hasRoute('/users');
    
  • Parameters

    • req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
    • route: (keyof Schema extends string
          ? keyof ReturnType<ExtensionFn> | string & keyof Schema | `${string & keyof Schema}/:id`
          : never) | (keyof Schema extends string
          ? keyof ReturnType<ExtensionFn> | string & keyof Schema | `${string & keyof Schema}/:id`
          : never)[]
    • method:
          | "GET"
          | "HEAD"
          | "POST"
          | "PUT"
          | "DELETE"
          | "CONNECT"
          | "OPTIONS"
          | "TRACE"
          | "PATCH"
          | (
              | "GET"
              | "HEAD"
              | "POST"
              | "PUT"
              | "DELETE"
              | "CONNECT"
              | "OPTIONS"
              | "TRACE"
              | "PATCH")[] = ...

    Returns boolean

    • Check if the request matches the route and method.
    • Useful for middleware.
    api.isOp(req, 'users', 'GET');
    
  • Parameters

    • path: string | Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>

    Returns string

    Remove the API's prefix from a path

    api.relpath(req);
    // '/api/users' --> 'users'
  • Returns Promise<undefined | Error>

    Start the API Server

    api.start().then((err) => {
    if (err) {
    console.error(err);
    }
    else {
    console.log(`API is running on port ${api.config.port}`);
    }
    });