A simple plugin for routing-controllers which allows to inject param from multiple sources.
npm install routing-controllers-multiparam --save
(or the short way with NPM v5):
npm i routing-controllers-multiparam
This package is only a plugin, so you have to install the routing-controllers
package because it can't work without it.
The usage of this module is very simple. All you need is:
import { JsonController, Post, createExpressServer } from "routing-controllers";
// import the `@MultiParam` decorator and `ParamType` enum from the module
import { MultiParam, ParamType } from "routing-controllers-multiparam";
// declare the controller class using routing-controllers decorators
@JsonController()
class ProductsController {
// example use case:
// register action on two routes and get `categoryId` param from query or path so both routes will work
@Get("/products")
@Get("/categories/:categoryId/products")
getProductsByCategory(
// use the `@MultiParam` decorator to define the sources of the param to inject
@MultiParam("categoryId", { required: true, allow: [ParamType.QueryParam, ParamType.Param] })
categoryId: string,
) {
return {
categoryId,
};
}
}
// start the server
createExpressServer({ controllers: [SampleController] }).listen(3000);
And that's it! This will lead to inject the first non-undefined value from the list of sources, so when you specify categoryId
param in path but not as a query string, it will be injected. It works just like switch-case - finds first source that exist.
The @MultiParam
decorator has two overloads:
export function MultiParam(options: NamedParamOptions): ParameterDecorator;
export function MultiParam(paramName: string, options: UnamedParamOptions): ParameterDecorator;
NamedParamOptions
- a type of object that propertyallow
can be a dictionary of allowed types:
{
required?: boolean;
allow: {
[P in ParamType]?: string | string[];
};
};
So the usage is just like this:
@MultiParam({ allow: {
[ParamType.QueryParam]: ["api_key", "apiKey"],
[ParamType.HeaderParam]: "X-Auth-Api-Key",
}})
UnamedParamOptions
- a type of object that propertyallow
can beParamType
or array ofParamType
{
required?: boolean;
allow: ParamType | ParamType[];
};
It can be used only with paramName
parameter when you want to get the param from multiple source but which is avaible on the same name:
@MultiParam("apiKey", { allow: [ParamType.QueryParam, ParamType.HeaderParam] })
- param normalization doesn't work - number params aren't casted from string (TBD after routing-controller
0.8.x
release) - there's no validation and transforming options (only primitives are supported)
If you need more examples of usage, go to the sources and check unit tests file (/src/decorators/MultiParam.spec.ts
).
If you have questions or new features/ideas, feel free to open an issue on GitHub repository.
0.1.0
- initial version with basic
@MultiParam
decorator support