Coder Social home page Coder Social logo

tsoa's Issues

`Error: Unknown type: TypeLiteral` when model contains nested objects

$ tsoa routes
There was a problem resolving type of 'Institution'.
Error: Unknown type: TypeLiteral
    at ResolveType (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/resolveType.js:27:15)
    at /Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/resolveType.js:137:23
    at Array.map (native)
    at getModelTypeProperties (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/resolveType.js:127:14)
    at generateReferenceType (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/resolveType.js:56:26)
    at ResolveType (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/resolveType.js:40:25)
    at Object.ResolveType (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/resolveType.js:38:16)
    at MethodGenerator.Generate (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/methodGenerator.js:23:34)
    at /Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/controllerGenerator.js:33:58
    at Array.map (native)
    at ControllerGenerator.buildMethods (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/controllerGenerator.js:33:14)
    at ControllerGenerator.Generate (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/controllerGenerator.js:23:27)
    at /Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/metadataGenerator.js:47:58
    at Array.map (native)
    at MetadataGenerator.buildControllers (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/metadataGenerator.js:47:14)
    at MetadataGenerator.Generate (/Users/kjensen/.nvm/versions/node/v7.5.0/lib/node_modules/tsoa/dist/metadataGeneration/metadataGenerator.js:22:32)

Here's my controller:

import { Institution } from "../model/Institution";
import { Controller, Route, Get } from "tsoa";
import { MockInstitutionsService } from "../service/MockInstitutionsService";
import { InstitutionsService } from "../service/InstitutionsService";

@Route("institutions")
export class InstitutionsController extends Controller {

  service: InstitutionsService = new MockInstitutionsService();

  @Get("{id}")
  public async findById(id: string): Promise<Institution> {
    return await this.service.findById(id);
  }

}

Here's my model:

export interface Institution {
  id: string,
  name: string,
  logo: string,
  colors: {
    primary: string,
    gradient: string[]
  }
}

Here's my tsoa.json:

{
  "swagger": {
    "outputDirectory": "./dist",
    "entryFile": "./src/index.ts",
    "host": "localhost:3000",
    "basePath": "/v1"
  },
  "routes": {
    "basePath": "/v1",
    "entryFile": "./src/index.ts",
    "routesDir": "./src",
    "middleware": "express"
  }
}

Support implicit return types

Currently, the only way to mark a controller method's corresponding swagger definition is with explicit type notation:

@Route('GetTest')
export class GetTestController {

  @Get()
  public async getModel(): Promise<TestModel> {
    return new ModelService().getModel();
  }
}

The following edit would break generation:

@Route('GetTest')
export class GetTestController {

  @Get()
  public async getModel() {
    return new ModelService().getModel();
  }
}

If possible, we should find a way to get the 'implicit' type from a class method. This seems like it should be possible given that editors calling into the language service can do it.

Buffer Type is not supported

export interface FooData {
    id: string;
    jsonData: Buffer;
}

Error: No matching model found for referenced type Buffer

We should map Buffer to string.

tsc fails to compile if tsoa is installed globally

I'm a typescript noob so this is probably something I'm doing wrong, but I can't figure it out...

I'm using nvm and have tsoa installed globally:

npm install -g tsoa

tsc then gives me this error:

endpoints/endpoints.ts(2,38): error TS2307: Cannot find module 'tsoa'.

which is the line where I import tsoa. My module resolution strategy is set to node, and I think that's correct. Could paths be conflicting in tsconfig.json?

    "paths": {
      "*": [
        "models/*",
        "endpoints/*",
        "generated/*"
      ]
    }

Help?

How to give endpoints a tag? (all go to default)

Hi, totally love this package and I am using the example to publish my own API.
Not sure this is an issue or I did not figure out to do it.
How to give endpoints a tag? (all go to default now and collapsed)
Can i leave this expanded by default?
Thanks, you rock.

Dependency Injection / Possible issue with reflect-metadata

I'd like to add dependency injection to the controllers. I am no expert on IoC / DI frameworks on JavaScript, but i found this nice project: http://inversify.io/

There are some issues when using the required reflect-metadata npm package in swagger-ts.

The decorators can't be compiled correctly. No idea if I am just to stupid to use inversify or if there is a real issue.

But as reflect-metadata is a pretty common package, we should have a look at this.

Cannot install tsoa >= 0.0.45

Looks like the location of cli.js changed

C:\Users\dave\Desktop\Code\blah>npm install --save [email protected]
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\dave\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" "--save" "[email protected]"
npm ERR! node v6.3.1
npm ERR! npm  v3.8.5
npm ERR! path C:\Users\dave\Desktop\Code\blah\node_modules\tsoa\dist\cli.js
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall chmod

npm ERR! enoent ENOENT: no such file or directory, chmod 'C:\Users\dave\Desktop\Code\blah\node_modules\tsoa\dist\cli.js'
npm ERR! enoent ENOENT: no such file or directory, chmod 'C:\Users\dave\Desktop\Code\blah\node_modules\tsoa\dist\cli.js'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

If I grab the tgz from https://registry.npmjs.org/tsoa/-/tsoa-0.0.47.tgz
cli.js is in package\dist\src\cli.js

Probably need to move the file back, or change:
https://github.com/lukeautry/tsoa/blob/master/package.json#L58-L60

Broken by 49730cf AFAICT

Middleware decorators

Hello,

it would be great to have some kind of Middleware decorators, where you can give middlewares to run before (or even after) a controller method. Middlewares could be on a separate layer or even special controller methods.

e.g.

@Route('Users')
export class UsersController {

    @Middleware
     public validate(request: express.Request, response: express.Request, next: function) {
        // TODO: implement a middleware
    }

    @Middleware
     public render(request: express.Request, response: express.Request, next: function) {
        // TODO: implement a rendering middleware
    }

    @MiddlewareBefore(UserController.validate)
    @MiddlewareAfter(UserController.render)
    @Get('{id}')
    public async getUser(id: number, @Request() request: express.Request): Promise<User> {
        // TODO: implement some code that uses request as well
    }
}

With this feature, existing Node.js projects would be much easeier to migrate into a tsoa project and also middleware pattern is essential part of Node.js applications.

It's could be an issue how to handle middleware chains, so e.g. MiddlewareBefore could contain an array of middlewares, or multiple decorators could be attached.

If we discuss the details I can help with implementation.
Thanks!

Bug with Date type.

Hi!

I noticed a but with a Date Type:

import { Get, Route } from 'swagger-ts';

export interface Hello {
	date: Date;
}

@Route('api/hello')
export class HelloController {
    @Get()
    public async getHello(): Promise<Hello> {
        thow "not implemented";
    }
}

/home/foo/projects/spielwiese/swagger-ts-bug/node_modules/swagger-ts/dist/metadataGeneration/resolveType.js:48
throw new Error(Multiple matching models found for referenced type ${typeName}; please make model names unique.);
^

Error: Multiple matching models found for referenced type Date; please make model names unique.

Cannot run tsoa when installed globally

npm install -g tsoa
tsoa --help
module.js:442
    throw err;
    ^

Error: Cannot find module 'C:\Users\dave\AppData\Roaming\npm/package.json'
    at Function.Module._resolveFilename (module.js:440:15)
    at Function.Module._load (module.js:388:25)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at getPackageJsonValue (C:\Users\dave\AppData\Roaming\npm\node_modules\tsoa\dist\cli.js:107:25)
    at Object.<anonymous> (C:\Users\dave\AppData\Roaming\npm\node_modules\tsoa\dist\cli.js:33:18)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.runMain (module.js:575:10)
    at run (bootstrap_node.js:352:7)
    at startup (bootstrap_node.js:144:9)
    at bootstrap_node.js:467:3

Doesn't work.

vs

npm install tsoa
node ./node_modules/tsoa/dist/cli.js --help
Usage: node_modules\tsoa\dist\cli.js <command> [options]

Commands:
  swagger  Generate swagger spec
  routes   Generate routes

Options:
  --help, -h  Show help                                                [boolean]

Works.

Number type and decimal

We can not use parameters validation with number if we expect float/decimal because there are always parsed as int...

const parsedNumber = parseInt(numberValue, 10);

Change to parseFloat maybe as float is a superset of int. Or Maybe implements a Type('float') decorator or something.

Best regards.

@Inject not working in `tsoa swagger` generator

I installed tsoa about 4 days ago and I created some routes with injected parameters, but when I cloned my project today and run swagger there was an error Error: Error generate parameter method: me argument: req Error: Parameter [object Object] doesn't have a valid type assigned., it's seems that there were some breaking changes in the last few days, but version number stayed the same.

TSOA with Rabbitmq

i have used this library for swagger api and i'm sending this request to rabbitmq using this function

import { configuration, random, uuid, amqp } from '../config';
const EventEmitter = require('events');

const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const createClient = () => amqp.connect(configuration.amqpUrl)
    .then((conn) => conn.createChannel())
    .then((channel: any) => {
        // create an event emitter where rpc responses will be published by correlationId
        channel.responseEmitter = new EventEmitter();
        channel.responseEmitter.setMaxListeners(0);
        channel.consume(REPLY_QUEUE,
            (msg: any) => channel.responseEmitter.emit(msg.properties.correlationId, msg.content),
            { noAck: true });
        return channel;
    });

const sendRPCMessage = (channel: any, message: any, rpcQueue: any) => new Promise((resolve, reject) => {
    const correlationId = uuid.v4();
    // listen for the content emitted on the correlationId event
    try {
        channel.responseEmitter.once(correlationId, resolve);
        channel.sendToQueue(rpcQueue, new Buffer(JSON.stringify(message)), { correlationId, replyTo: REPLY_QUEUE })
    } catch (error) { reject(error) }

});

and the on the controller i use

   public async postSurvey(survey: Survey): Promise<Survey> {
        var obj: Survey;
        await createClient().then((channel) => {
            sendRPCMessage(channel, survey, "survey_q_req").then((data) => {
                obj = data as Survey;
            }).catch((error) => { console.log(error) });
        }).catch((error) => { console.log(error) });
        return obj
    }

but code seems having issue with getting response. did i do anything wrong on controller level?

Support for parameters in PUT

I'm not sure if I'm doing something wrong but this controller doesn't work as I would expect:

@Put('{id}')
  public async update(id: number, activity: ActivityModel) : Promise<ActivityModel> {
    return this.activityService.update(id, activity);
 }

The id parameter is completly ignored in this case. Swagger doesn't know about the id parameter and I cannot set it in the swagger UI. It only provides a nice UI for the activity.

I'm am doing something wrong or is this case not support yet?

koa route function has to return promise

Otherwise it will fail when you await something inside the controller.

Line 30 in /src/routeGeneration/templates/koa.ts

Just add return before promiseHandler(...) call.

I really like this project, so i hope to contribute in the future, but for now, i would be really grateful for this quick fix with next release, thanks.

Support generic type parameter and return type

Return type:
Current only support return Promise<XXX>, when return Promise<Response<XXX>> or Response<XXX>, cli throw error "No matching model found for referenced type T".

Paramter type:
use generic type in parameter can generate definition file, but swagger show parameter's schema is undefined.

Can you support it? thank you.

Typescript Union Types Fail Model Validation

If I declare a property in a model with a union type:

export class Example {
     public $key?: string | null = null;
}

The resulting model is generated as such:

'$key': { typeName: 'object', required: false }

Since there is no corresponding 'object' model definition, an error results at run time.

unexpected error when running tsoa swagger

An error occur when trying to run tsoa swagger:
node_modules\tsoa\dist\cli.js swagger

Options:
--help, -h Show help [boolean]
--configuration, -c tsoa configuration file; default is tsoa.json in the
working directory [string]

Cannot read property '0' of undefined

The project is in Hapi framework.

Controllers:

// decorator for swagger
@Route("LBB")
export class LBB {

    // service return fake highways data
    @Get("highways")
    getHighways(): Highway[] {
        return[
            {"routeid": 1333, "Name": "I 15N"},
            {"routeid": 1332, "Name": "I 10W"},
            {"routeid": 1330, "Name": "Tim Sweet Blvd"}
            ];
    }

    // service return all customers
    @Get("customers")
    getCustomers(): Promise {
        return new Promise((resolve, reject) => {
            runQuery(config.customers, resolve, reject);
        });
    }

    // service return particular customer by ID
    @Post("customerByID")
    getCustomerByID(customer: Customer): Promise {
        let newQuery = `select * from lb_customers where cus_id = ${customer.cus_id}`;
        return new Promise((resolve, reject) => {
            runQuery(newQuery, resolve, reject);
        });
    }
}

Routes:

export let register: Register = (server, options, next) => {
    server.route([
    {
        // GET method to return fake highways data
        method: "GET",
        path: "/highways",
        config: {
            handler: (request, reply) => {
                reply(lbb.getHighways());
            }
        }
    },
    {
        // GET method to get list of all customers
        method: "GET",
        path: "/customers",
        config: {
        handler: (request, reply) => {
            // TODO: validate requst prameters based on business rules
            lbb.getCustomers()
            .then((customers) => reply(customers))
            .catch((err) => reply (err));
        }
    }
    },
    {
        // POST method to get a customer by ID
        method: "POST",
        path: "/LBB/customerByID",
        config: {
            handler: (request, reply) => {
                lbb.getCustomerByID(request.payload)
                .then((customer) => reply(customer))
                .catch((err) => reply(err));
            },
            validate: {
                payload: {
                    cus_id: Joi.number().required(),
                    cus_name_short: Joi.string(),
                    cus_name_long: Joi.string(),
                    cus_log_modes: Joi.string(),
                    cus_log_type: Joi.string(),
                    cus_log_cloud_url: Joi.string(),
                    cus_log_file_path: Joi.string(),
                    cus_language: Joi.string(),
                    cus_email: Joi.string(),
                    cus_login_banner: Joi.string()
                }
            }
        }
    }
    ]);
    next();
};

Server:

const server = new Hapi.Server();
    server.connection({
        "port": config.port
    });
server.register(LBB, {
        routes: {
            prefix: "/LBB"
        }
    }, (err) => {
        if (err) {
            throw err;
        }
    });
server.start(config.err);

string literal enum types not working...

I'm having trouble with string literal enums.

I have defined this:

export type Status = 'Happy' | 'Sad';

Yet I get this error when I try to add it to my User model:

Cannot read property 'text' of undefined

Any suggestions?

model:

export interface User {
    id: number;
    email: string;
    createdAt: Date;
    status?: Status;
}

controller:

    @Get('{userId}')
    public async Get(userId: number): Promise<User> {
        let user: User = {
            createdAt: new Date(),
            email: 'test2',
            id: userId,
            status: 'Happy'
        };
        return user;
    }

Namespace support

As it turns out, following won't work:

export interface TestModel extends Model {
//...
  modelsObjectIndirectNS: TestSubModelContainerNamespace.TestSubModelContainer;
  modelsObjectIndirectNS2: TestSubModelContainerNamespace.TestSubModelContainer2;
  modelsObjectIndirectNS_Alias: TestSubModelContainerNamespace_TestSubModelContainer;
  modelsObjectIndirectNS2_Alias: TestSubModelContainerNamespace_TestSubModelContainer2;
//...
}

export namespace TestSubModelContainerNamespace {
  export interface TestSubModelContainer {
    [key: string]: TestSubModel2;
  }

  export interface TestSubModelContainer2 {
    [key: string]: TestSubModel2;
  }
}
export type TestSubModelContainerNamespace_TestSubModelContainer = TestSubModelContainerNamespace.TestSubModelContainer;
export type TestSubModelContainerNamespace_TestSubModelContainer2 = TestSubModelContainerNamespace.TestSubModelContainer2;

Hopefully, I'll be able to address that with PR, yet if anyone willing to give a hint, that would be great

Support custom swagger definition parts

It is possible to add the possibility to define a custom swagger.json-skeleton which is used in swagger/specGenerator.ts, possibly like this:

  public GetSpec() {
    const customSpec = require('path-to-spec-file');
    const spec: Swagger.Spec = Object.assign(customSpec, {
      basePath: this.options.basePath,
      consumes: ['application/json'],
      definitions: this.buildDefinitions(),
      host: this.options.host,
      info: {
        description: this.options.description,
        license: {
          name: this.options.license
        },
        title: this.options.name,
        version: this.options.version
      },
      paths: this.buildPaths(),
      produces: ['application/json'],
      swagger: '2.0'
    });

    if (this.options.host) { spec.host = this.options.host; }

    return spec;
  }

Or what is your suggested way to add for example security information?

Providing configuration to controllers

I'd like to pass some settings to my controllers to configure them correctly (db connection details as an example).

Is there a nice way to do this? My current thought is to have them require a static settings object that I set up externally.

Ideally I'd like to do this by passing an object to their constructor, but if there was a post construction init method that'd probably be fine.

Thanks :)

JWT authentication

Hello @lukeautry thanks for the hard work. one question!! how do we enable JWT authentication i couldn't see that in example project can you post some code sample or update example project

Thanks

Please fix line endings to LF

To reproduce problem:

git clone https://github.com/lukeautry/tsoa-example
cd tsoa-example
npm i
npm start

Got error:
tsoa swagger --swaggerDir=./dist --entryFile=./src/server.ts --host=localhost:3000 --basePath=/v1

/usr/bin/env: «node\r»: No such file or directory
(like there: nwutils/nw-builder#75)

To fix that issue on Ubuntu 16.04 (and I suppose on other linux and MacOS as well) I replaced line endings for the file node_modules/tsoa/dist/cli.js from CRLF to LF (using WebStorm, I suppose that other editors support that feature as well and probably there is exist some command line tool to do it)

Thanks you guys, I really like tsoa - wish you success!

Send file / return raw binary "application/octect-stream" or "image/jpeg" ...

Hello,

I am struggling on something I wan't to do and it's seems not possible to do it with the tsoa framework.
Returning raw data or file is not allowed by using a standard controller. Obviously, I can define my own express route and custom controller but I can't add the spec to swagger.json automatically because when I fill the spec field in tsoa.json it is overriding every paths !

Proposal:

  • merge tsoa.json "swagger"."spec" recursively instead of overriding at the first level.
  • allow more customization of controller and extend the router/promiseHandler.

My solution:

  • Defining custom route with express
  • Custom tsoa.spec.json merged with my own script
    (not yet done wanna see if you guys have another way around or if I missed something?)

Regards.

PS: It is whats looks like my tsoa.json if it can help

{
    "swagger": {
        "outputDirectory": "./dist",
        "entryFile": "./src/server.ts",
        "host": "localhost:3000",
        "basePath": "/v1",
        "spec": {
            "paths": {
                "/Data/GetUserProfilePicture/{userId}": {
                    "get": {
                        "operationId": "getUserProfilePicture",
                        "produces": [
                            "image/jpeg"
                        ],
                        "responses": {
                            "200": {
                                "description": "",
                                "examples": {},
                                "schema": {
                                    "type": "binary"
                                }
                            }
                        },
                        "description": "Get an user profile picture",
                        "parameters": [
                            {
                                "description": "",
                                "in": "path",
                                "name": "userId",
                                "required": true,
                                "type": "integer",
                                "format": "int64"
                            }
                        ]
                    }
                }
            }
        }
    },
    "routes": {
        "basePath": "/v1",
        "entryFile": "./src/server.ts",
        "routesDir": "./src",
        "middleware": "express"
    }
}

RoutesConfig error

When providing iocModule in the RoutesConfig it checks to see if the file exists at the path inside the string name but the docs say:

Note that the path is relative to the routesDir and does not contain the extension.

I can fix this, but I am not sure if you want to fix it via the docs or code.

Also as a heads up this bug: vvakame/typescript-formatter#87 is causing a build failure for your code. Potential solutions would be to lock down to version (4.1.2) until its fixed or pass in vscode param.

POST parameters in the body

At the moment when creating a POST method that takes parameters, these get passed in the URL.
Is is possible to pass them as post parameters in the body instead?

This isn't really a problem, but it does seem a little weird. I haven't seen POST parameters passed in the URL before.

Support for class-based model

part of my model is class-based ( because it need to be decorated for the object-relational mapping and should have a default constructor ) and
although I would be able to declare additional interfaces, this would lead to duplicating all the property definitions of the classes to the corresponding interfaces.

Do you have any plan to support a class-based model?

Error, Multiple matching models found

I have this error when generating routes or swagger

There was a problem resolving type of 'FindForLocationResponse'.
Error: Multiple matching models found for referenced type FindForLocationResponse; please make model names unique.

It's true, i have two interfaces with the same name, but they are in different packages,
one is used internally by the service,
and the other in the controller (for tsoa router and swagger generation)

Is there a way to fis this error other then rename the interface ?

Use external middlewares in tsoa

I wonder if there is some simple way to use external libraries (such as passport.js) with tsoa. I saw injection of req, but often we need res and next as well. The ideal situation for me is to pass req res next to some middleware (in i.e. /services) that would implement logic of the endpoint.

Support dependency injection for controllers

As discussed already here and here it would be very convenient that the default templates support controllers managed by a DI-framework like inversifyJS.
I added a PR to solve the problem by adding the relative path to the IOC-module exporting the kernel in the tsoa.json.

(question): roadmap/direction

Nice project! Have a question....

Are you trying to build something that you can generate swagger from your typescript controllers/models OR are you trying to build a middleware that lets you consume the swagger spec and then define the biz logic via your project?

Unknown type: UnionType

Make a controller with a return result that includes a string union

interface Result {
    value: 'success' | 'failure';
}

Then try generate routes with tsoa.
You get the error: Unknown type: UnionType

Issue with the "date" type in an @Example decorator

I tried to annotate the method of a controller using :

@Example<UpperResult>({
    name: "test",
    upperName: "TEST",
    date: new Date(),
})

But the date part doesn't seem to be generated in the "swagger.json" file.

Any idea?

Roadmap

  • What features are missing?
  • What features are on the roadmap?

Security definitions

Currently tsoa doesn't provide mechanism to set security decorators for methods in controller. It would be useful to extend library with such decorators.
My expectation is that developer could set up decorator in next way
@Route("users") export class Index { constructor() { }

`@Get()
@Oauth2Security({enabled: true, scope: ['read', 'write']})
public async Get(userId: string): Promise<UserData> {
    return findUser;
}

`

unhelpful error messages

When calling tsoa swagger or tsoa routes:

node_modules/.bin/tsoa routes

Options:
  --help, -h           Show help  [boolean]
  --configuration, -c  tsoa configuration file; default is tsoa.json in the working directory  [string]

Cannot read property 'toLowerCase' of undefined

users.ts:

import {Get, Route, Post} from 'tsoa'
import * as Models from "../models"
import { getCxn } from "../db-util"
import * as Api from "../api-common"

export interface LoginArgs {
    email: string
     token: string
}
@Route('Users')
export class UsersController {
    @Post()
    public async createUser(email: string, token:string): Promise<Api.User> {
      return {} as Promise<Api.User>
//        return await getCxn().then(Models.loginUser(email, token, "DevManual"))
    }
}

api-common.d.ts:

export type AuthSource = "Cognito" | "Facebook" | "DevManual"

export interface DayPlan {
    title: string
}

export interface UserAuth {
    id: number
    token: string
    source: AuthSource
}

export interface User {
    email: string; days: DayPlan[]
}

tsoa.json:

{
    "swagger": {
        "outputDirectory": "./dist",
        "entryFile": "./src/controllers/users.ts",
        "basePath": "/v1",
        "name": "macrofit",
        "description": "macrofit"
    },
    "routes": {
        "basePath": "/api/v1",
        "entryFile": "./src/controllers/users.ts",
        "routesDir": "./src"
    }
}```

regarding your commit "handle date as query param": we need the "format:-date-time" in the swagger

Hi Luke,
Thanks a again but I think you just forgot a little detail. We noticed in your change-set handle date as query param that you added a "format" to the label definition... but that 'format' does nto appear in the actual swagger.json and, so, it does not look good in the Swagger UI. It still appears as string. I think your just need to add that format to the swagger.json generator.

     Cheers!, Pablo.

Handling of Response Codes / Types

I'd love to have status codes and error response types to be defined in controllers.
So we can have it in swagger:
http://swagger.io/specification/#responsesDefinitionsObject

Example:

@get('Foo')
@response([200,201,400], [TestModel, void, FancyErrorModel])
public async getFoo(): Promise {
throw {
message: 'error thrown',
status: 400
};
}

Two more key ideas:

  1. The default is @response([200], [TestModel])

  2. There is a template to provide a different response code "tsoa.Response"

@get('Foo')
@Responses([200,201,400], [TestModel, TestModel, FancyErrorModel])
public async getFoo(): Promise<Response> {
return await Response.withStatus(this.getModel(), 201);
}

how to pass back better custom error message and status code on 400 404..

Hi Luke,
Thanks again for your help before with datetime. Now we have this minor annoyance. When we have a GET with various parameters, say p1,..p,n2 and .. px is number but customer send string... the current error code is 400 and not message.
We noticed that the router has a 'next' function but could not figure out how to use it.
We want to return a proper custom error message and code.
Eventually, I think, we we know your code better we may try to help you, but for now we are to newbies.
Thanks!, Pablo.

Support enums

Acceptance Criteria:

  • Enum properties/return types should generate valid swagger enum types
  • Routing layer should validate enums

Automatic controllers discovery

Hi Luke, we spoke by email some days ago! I started my tests with Tsoa and, so far, it works pretty well! I'm currently doing a first POC using Express. I'm going to have some questions and I'll ask them as issues, if you don't mind!

First, I think it would be nice to not have to reference the controllers in order for Tsoa to discover them... Maybe a "controllerBase" config could be used and, any @Route() decorated class found in files under this base could be automatically found? Is this something that can be done?

Integrate with `routing-controllers`

routing-controllers is a extensive decorator library for Express and TypeScript. It, however, does not have support for Swagger ( yet ;) ).

Rather than re-invent the wheel it would be nice to have adapters for use with other libraries like this. I've spoken to @pleerock and he's interested in this effort too.

Additionally, there is class-validators which is a decorator pattern for property validation that might be worth thinking about too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.