0.0.7 ā¢ Published 2 years ago
speedily-js v0.0.7
speedily-js allows you to quickly create an express server with minimal code
Install
npm install speedily-js
Usage
Simple
import { Server, Controller } from 'speedily-js';
const server = new Server(3000);
const homeController = new Controller('/home').get('/', () => {
return 'Home';
});
server.setControllers([homeController]);
server.run();
Using the parameters
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'))
);
Post data
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 }
);
Throw an error
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');
}
);
Authenticate your controllers
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)
...
Authenticate a specific route
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
Author
š¤ Mickael Pezzoni
- Github: @mickael-pezzoni
š¤ Contributing
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.
Show your support
Give a āļø if this project helped you!
š License
Copyright Ā© 2022 Mickael Pezzoni. This project is ISC licensed.