olivierlsc/swagger-express-ts

How to bind controller if I am not using inversify-express-utils? The routes are not detected otherwise

shareefsakk opened this issue · 2 comments

How to bind controller if I am not using inversify-express-utils? The routes are not detected otherwise

@shareefsakk ,

Here an example.

src/index.ts :

import * as express from "express";
import { CarsController } from "./cars.controller";
import * as swagger from "swagger-express-ts";
const app = express();

app.use("/api-docs/swagger", express.static("swagger"));
app.use(
    "/api-docs/swagger/assets",
    express.static("node_modules/swagger-ui-dist")
);
app.use(
    swagger.express({
        definition: {
            info: {
                title: "My api",
                version: "1.0",
            },
            externalDocs: {
                url: "My url",
            },
            models: {
                Car: {
                    properties: {
                        id: {
                            type:
                                swagger.SwaggerDefinitionConstant.Model.Property
                                    .Type.NUMBER,
                        },
                        name: {
                            type:
                                swagger.SwaggerDefinitionConstant.Model.Property
                                    .Type.STRING,
                            required: true,
                        },
                    },
                },
            },
        },
    })
);

app.use(new CarsController().getRouter());

app.listen(3000);
console.info("Server is listening on port 3000...");

and

src/cars.controller.ts :

import * as express from "express";
import {
    ApiPath,
    ApiOperationGet,
    SwaggerDefinitionConstant,
} from "swagger-express-ts";

@ApiPath({
    path: "/cars",
    name: "Car",
})
export class CarsController {
    private router: express.Router;

    constructor() {
        this.router = express.Router();
        this.router.get("/cars", this.getCars);
    }

    @ApiOperationGet({
        description: "Get cars list",
        responses: {
            200: {
                type: SwaggerDefinitionConstant.Response.Type.ARRAY,
                model: "Car",
            },
        },
    })
    getCars(
        request: express.Request,
        response: express.Response,
        next: express.NextFunction
    ): void {
        const cars = [
            {
                id: 1,
                name: "BMW",
            },
            {
                id: 2,
                name: "MERCEDES",
            },
        ];
        response.json(cars);
    }

    getRouter(): express.Router {
        return this.router;
    }
}

I hope it help you.

I close this issue and don't hesitate to reopen it if you want.