thiagobustamante / typescript-rest

This is a lightweight annotation-based expressjs extension for typescript.
MIT License
525 stars 108 forks source link

How to use loadServices ? #47

Closed msieurtoph closed 5 years ago

msieurtoph commented 6 years ago

I used and adapted the code that I found in the README.md :

In /xx/yy/api-server.class :

const app = express();
const api = express.Router();
Server.loadServices(api, '../../api/*');
this.api.use('api', api);

In /api/*, I have all my decorated services, such as :

@Path('/someResources')
export class SomeResources { ... }

I expected that http://localhost:3000/api/someResources would serve me the service SomeResources, but it does not. It seems that it did not load anything at start ...

Can you help me using this ?

Note that when I import the service and use Server.buildServices(), the url http://localhost:3000/someResources works perfectly !

vrudikov commented 6 years ago

+1 it seems API was changed. I need to reflect it in boilerplate project

ttruongatl commented 6 years ago

"typescript-rest": "^1.6.1" Folder structure

src
 |---controllers
 |        |----AuthController.ts
 |        |----UserController.ts
 |        |----index.ts
 |---api-server.ts

UserController.ts

@Path('/api/users')
export class UserController {
....
    @Security(['admin'])
    @Path('')
    @GET
    async getUsers(): Promise<UserModel[]> {
        // Get all of users
    }

    @Path(':id')
    @GET
    async getUser(@PathParam('id') id: string): Promise<UserModel> {
        // Get User by id.

    }
}

index.ts

import { UserController, } from './UserController';
import { AuthController } from './AuthController';

export default [
    // controllers
    UserController,
    AuthController,
];

api-server.ts

....
import { UserController } from './controllers';
....
export class ApiServer {
    private app: express.Application;
    private server: http.Server = undefined;

    constructor() {
        this.app = express();
        this.config();
        this.mongoSetup();

        Server.useIoC();
        Server.buildServices(
            this.app,
            ...controllers,
            .....
        )
    }
}

It works for me with 2 APIs:

* /api/users -> get all of users
* /api/users/<id> -> get user by Id.