Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

index.js doesn't export the method 'Controllers.load' in './lib/controllers' #1

Closed
myfjdthink opened this issue Jun 4, 2016 · 3 comments

Comments

@myfjdthink
Copy link

I use ts-express-decorators like a npm package , but it doesn't export the initialise method 'Controllers.load' in './lib/controllers', I can't initialise express routes on the outside of this package.

@Romakita
Copy link
Collaborator

Romakita commented Jun 4, 2016

Hello myfjdthink,
Ts-express-decorators is flagged as beta actually and the readme.md isn't updated to use this package correctly. But you have an example of use in example folder. You can try this example :
Your server.ts

import * as Express from "express";
import {ServerLoader} from "ts-express-decorators/server-loader";
import Path = require("path");

export class ExampleServer extends ServerLoader {
    /// In your constructor set the global endpoint and configure the folder to scan the controllers.
    /// You can start the http and https server.
    constructor() {
        super();

        let appPath = Path.resolve(__dirname);

        this.setEndpoint('/rest')
            .scan(appPath + "/controllers/**/**.js") // Component scan like Spring MVC. Specify you controllers directory
            .createHttpServer(8000)
            .createHttpsServer({
                port: 8080
            });

    }

    /// This method let you configure the middleware required by your application to works.
    public importMiddlewares(): ExampleServer {
        let morgan = require('morgan'),
            cookieParser = require('cookie-parser'),
            bodyParser = require('body-parser'),
            compress = require('compression'),
            methodOverride = require('method-override'),
            session = require('express-session');

        this
            .use(morgan('dev'))
            .use(ServerLoader.AcceptMime("application/json"))
            .use(bodyParser.json())
            .use(bodyParser.urlencoded({
                extended: true
            }))
            .use(cookieParser())
            .use(compress({}))
            .use(methodOverride());

        return this;
    }

    /// Customize this method to manage all errors emitted by the server and controllers.
    public onError(error: any, request: Express.Request, response: Express.Response, next: Function): void {

        console.error(error);

        response
            .status(500)
            .send('Internal Server error');

        next();
    }

   /// Set here your check authentification strategy.
    public isAuthenticated(request: Express.Request, response: Express.Response, next: Function): boolean {


        return true;
    }

    // Start your server. Enjoy it !
    static Initialize(): Promise<any> {

        console.debug('Initialize server');

        return new ExampleServer()
            .start()
            .then(() => {
                console.debug('Server started...');
            });
    }
}

And create a calendarCtrl.ts in your controllers directory :

import {Controller, Get, PathParams, Request, Response} from "ts-express-decorators";
import * as Promise from "bluebird";
import * as Express from "express";

interface ICalendar{
    id: string;
    name: string;
}
/**
 * Add @Controller annotation to declare your class as Router controller. The first param is the global path for your controller.
 * The others params is the controller depedencies. 
 *
 * In this case, EventCtrl is a depedency of CalendarCtrl. All routes of EventCtrl will be mounted on the `/calendars` path.
 */
@Controller("/calendars")
export class CalendarCtrl {

    /**
     * Example of classic call. Use `@Get` for routing a request to your method.
     * In this case, this route "/calendar/classic/:id" are mounted on the "rest/" path (call /rest/calendar/classic/:id
     * to test your service).
     *
     * By default, the response is sent with status 200 and is serialized in JSON.
     *
     * @param request
     * @param response
     * @returns {{id: any, name: string}}
     */
    @Get('/classic/:id')
    public findClassic(request: any, response: any): ICalendar {

        return {id: request.params.id, name: "test"};
    }

    /**
     * Example of customised call. You can use decorators to inject express object like `response` as `@Response`,
     * `request` as `@Request` and `next` as `@Next`.
     *
     * Another decorator are available to access quickly to the pathParams request. `@PathParams` take an expression in
     * first parameter.
     *
     * @param request
     * @param id
     * @returns {{id: any, name: string}}
     */
    @Get('/annotation/test/:id')
    public findWithAnnotation(
        @Request() request,
        @PathParams('id') id
    ): ICalendar {

        console.debug('ID =>', id, request.params.id);

        return {id: id, name: "test"};
    }

    /**
     * Your method can return a Promise to respond to a request.
     *
     * By default, the response is sent with status 200 and is serialized in JSON.
     *
     * @param request
     * @param id
     * @returns {Promise<ICalendar>}
     */
    @Get('/annotation/promised/:id')
    public findWithPromise(
        @Request() request,
        @PathParams('id') id
    ): Promise<ICalendar> {

        console.debug('ID =>', id, request.params.id);

        return new Promise<ICalendar>((resolve, reject) => {
            resolve({
                id: id,
                name: "test"
            });
        });
    }

    /**
     * Your method can return a Promise to respond to a request.
     *
     * By default, the response is sent with status 200 and is serialized in JSON.
     *
     * @param request Express request
     * @param response Express response
     * @param id
     * @returns {Promise<ICalendar>}
     */
    @Get('/annotation/status/:id')
    public findAndChangeStatusCode(
        @Request() request: Express.Request,
        @Response() response: Express.Response,
        @PathParams('id') id: string
    ): Promise<ICalendar> {

        Logger.debug('ID =>', id, request.params.id);
        //
        return new Promise<ICalendar>((resolve, reject) => {

            response.status(202);

            resolve({
                id: id,
                name: "test"
            });
        });
    }
}

I hope it'll be work for you :)
@++

@myfjdthink
Copy link
Author

It worked! thanks lots.

@Romakita
Copy link
Collaborator

Romakita commented Jun 7, 2016

nice :)

@Romakita Romakita closed this as completed Jun 7, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants