Function createApiHandlerFactory

  • Creates a factory function, which is able to create a strong typed IApiHandler based instance.

    Type Parameters

    Parameters

    Returns ApiHandlerFactory<ExtendedApiHandler<THandler, TApiMethods>>

    The new function.

    Example

    // `npm i axios`
    import type { AxiosInstance } from "axios"
    import { createApiHandlerFactory, IApiHandler } from "@egomobile/api-utils"
    import { createServer, params } from "@egomobile/http-server"

    interface IGetUserByIdOptions {
    userId: string;
    }

    async function getApiClient(): Promise<AxiosInstance> {
    // return an `AxiosInstance` instance here
    // which is already authenticated
    // and ready-to-use
    }

    async function getAllUsers(this: IApiHandler): Promise<void> {
    const {
    getApiClient,
    request, response
    } = this

    // ...

    this.apiResponse()
    // ... do some more operations here
    .send()
    }

    async function getUserById(this: IApiHandler, options: IGetUserByIdOptions): Promise<void> {
    const {
    getApiClient,
    request, response
    } = this

    const {
    user
    } = options

    // ...

    this.apiResponse()
    // ... do some more operations here
    .send()
    }

    const createApiHandler = createApiHandlerFactory({
    getApiClient,

    "methods": {
    getAllUsers,
    getUserById
    }
    })

    const app = createServer()

    app.get("/users", async (request, response) => {
    const newHandler = createApiHandler({
    request, response
    })

    await newHandler.getAllUsers()
    })

    app.get(params("/users/:user_id", async (request, response) => {
    const newHandler = createApiHandler({
    request, response
    })

    await newHandler.getUserById({
    userId: request.params!.user_id
    })
    })

    await app.listen()

Generated using TypeDoc