speedily-js allows you to quickly create an express server with minimal code
npm install speedily-js
import { Server, Controller } from 'speedily-js';
const server = new Server(3000);
const homeController = new Controller('/home').get('/', () => {
return 'Home';
});
server.setControllers([homeController]);
server.run();
getOrFail
automatically throws a 400 error if the parameter could not be found
const productController = new Controller('/products')
.get('/', (context: Context) =>
productService.findAll([], context.queryParams.get('categoryId'))
)
.get('/:id', (context: Context) =>
productService.findOne(context.params.getOrFail<number>('id'))
);
You can use class-validator to check your dto.
class CreateProductDto {
@IsString()
@Length(4)
name!: string;
@IsString()
@IsOptional()
description!: string;
@IsNumber()
quantity!: number;
@IsNumber()
categoryId!: number;
}
const productController = new Controller('/products').post(
'/',
(context: Context) =>
productService.create(context.body.get<CreateProductDto>()),
{ bodyValidator: CreateProductDto }
);
const productController = new Controller('/products').post(
'/',
(context: Context) => {
throw new BadRequestError(`Why not`);
}
);
You can also create your own errors
export class CustomError extends HttpError {
constructor(message: string) {
super(418, message);
}
}
const productController = new Controller('/products').get(
'/',
(context: Context) => {
throw new CustomError(`Why not`);
// or
throw new HttpError(418, 'Why not');
}
);
const productController = new Controller('/products').get(
'/',
(context: Context) => {
return { status: 201, arg: {} };
}
);
function auth(jwt: string, context: Context): Promise<boolean> {
try {
verify(jwt, environnement.API_SECRET_JWT);
} catch (err) {
return false;
}
return true;
}
const productController = new Controller('/products')
.enableBearerAuth(auth)
...
You can also pass data to your routes and access them with
context.data
const productController = new Controller('/products').get(
'/:id',
(context: Context) =>
productService.findOne(context.params.getOrFail<number>('id')),
{
bearerAuthFnt: auth,
data: {
roles: ['admin', 'manager'],
},
}
);
A more complete example here
👤 Mickael Pezzoni
- Github: @mickael-pezzoni
Contributions, issues and feature requests are welcome!
Feel free to check [issues page](https://github.com/mickael-pezzoni/ speedily-js/issues). You can also take a look at the contributing guide.
Give a ⭐️ if this project helped you!
Copyright © 2022 Mickael Pezzoni.
This project is ISC licensed.