A flexible library for building fast API (Application program interface) and maintainable.
@11z/express is based on express framework.
kao,fastify ets.are not supported yet.
- Error handler such as 404 exception and global exception ✔
- Catch async error on all routes ✔
OOPandMVCbased routing or functionality are also supported ✔- Typescript support out of the box.
cjs,umdare also supported. ✔ - Route validation ✔
- Lighter, easier and maintainable ✔
👉 Some of these features are optional.
Note: You don’t need to install the express library. everything is included.
./server.ts
import express from '@11z/express'
// Initialize express.
const app = express()
// Listen for connections.
app.listen(4000, () => console.log('Server is up! visit: http://localhost:4000'))./server.ts
import express from '@11z/express'
// Initialize express.
const app = express()
// Register route.
app.get('/', (_req, res) => {
res.status(200).send('OK')
}) // visit: http://localhost:4000 => OK
// Listen for connections.
app.listen(4000, () => console.log('Server is up! visit: http://localhost:4000'))./ex.api.ts
import { Api, Get } from '@11z/express'
@Api()
export class ExampleApi {
@Get()
public helloWorld(): string {
return 'hello world!'
}
}./ex.ro.ts
import express, { Route } from '@11z/express'
import { ExampleApi } from './cat.api.ts'
@Route([ExampleApi], { router: express.Router() })
export class ExampleRoute {}./server.ts
import express, { Router } from '@11z/express'
import { ExampleRoute } from './ex.ro.ts'
// Initialize express.
const app = express()
// Router instance.
const router = new Router(app)
// Attach and register decorated route.
router.attach('/api/v1', [ExampleRoute])
// Listen for connections.
app.listen(4000, () => console.log('Server is up! visit: http://localhost:4000'))You need nodeJs install.
# with npm
npm i @11z/express
npm i @11z/core
# installing typescript
1. npm i -D typescript - in this case I'm using npm.
2. npx tsc --init - to create tsconfig.json file.As we all know, the library uses @decorator without enabling some additional features. Typescript will complain. You need to enable these additional features of Typescript. In the file
'tsconfig.json' Launch these:
{
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}That's it. let's get into coding! see example.
We provide all the Apis that you will need to create a flexible and maintainable application.
A class defined with methods for handling one or more requests.
- @param
urlurl path.
Example:
import { Api } from '@11z/express'
@Api()
export class ExampleApi {}A specific endpoint for HTTP requests.
- @param
methodhttp method type. - @param
urlurl path. - @param
statusstatus code.
Possible methods:
@Get(), @Post(), @Put(), @Patch(), @Delete()
Example:
import { Get } from '@11z/express'
export class ExampleApi {
@Get()
public helloWorld(): string {
return 'hello world!'
}
}A function which is called before the route handler.
- @param
midsexecute any code.
Example:
method middleware
import { Middleware } from '@11z/express'
export class ExampleApi {
@Middleware([
(req, res, next) => {
console.log('mid mounted before route bound.')
next()
}
])
public helloWorld(): string {
return 'hello world!'
}
}Example:
route middleware
import { Middleware } from '@11z/express'
@Middleware([
(req, res, next) => {
console.log('mid mounted before route bound.')
next()
}
])
export class ExampleRoute {}A named URL segments that are used to capture the values specified at their position in the URL.
- @param
namerequest type.
Possible params:
@Req(), @Res(), @Next(), @Params(), @Query(), @Body(), @Cookies(), @Headers(), @Ctx()
Example:
import { Req, Request, Body } from '@11z/express'
export class ExampleApi {
public helloWorld(@Req() req: Request, @Body() body: object): string {
// `req.body` regular use.
// instead of `req.body` use `@Body() param` with `body` => req.body
return 'hello world!'
}
}Validation middleware. A function which is called before the route handler.
- @param
schemaschema object.
Supported library: zod
Note: With some libraries besides
zodcan also be integrated with routing validation, but you just have to set it up yourself. Our developers are working on it to put everything convenient.
Example:
with zod
import { ValidateRequest, Validation } from '@11z/express'
import { object, string } from 'zod'
export class ExampleApi {
@Validation(object<ValidateRequest>({ body: object({ name: string() }) }))
public helloWorld(): string {
return 'hello world!'
}
}No docs description yet.
- @param
Apisapi handlers. - @param
routeOptionsroute options.
Example:
import express, { Route } from '@11z/express'
@Route([], { router: express.Router() })
export class ExampleRoute {}You can customize some Apis according to your needs.
Most come with middleware. It has to be flexible. Sure, we got it!
Example:
./api.middleware.ts
import { Middleware, UnauthorizedError } from '@11z/express'
// Check if user is not log in.
const Authenticated = () =>
Middleware([
(req, res, next) => {
if (req.isUnAuthenticated()) {
throw new UnauthorizedError('You are not logged in.')
}
}
])
// Example usage:
export class ExampleApi {
@Authenticated()
public helloWorld(): string {
return 'hello world!'
}
}In addition to the 5 common http methods
@Get(), @Post(), @Put(), @Patch(), @Delete()that we provided, there are some other http methods such asall, trace, head, options, etc.that we didn't provided. you can customize it to your needs.
Example:
./api.method.ts
import { METHOD_DECORATOR_FACTORY, PathParams } from '@11z/express'
// Head http method.
const Head = (url?: PathParams, status: number = 200) => METHOD_DECORATOR_FACTORY('head', url, status)
// Example usage:
export class ExampleApi {
@Head()
public helloWorld(): string {
return 'hello world!'
}
}The Router is a top-level class used to attach and register decorated route.
import express, { Router } from '@11z/express'
// Initialize express.
const app = express()
// Router constance.
const router = new Router(app)
// Attach and register decorated route.
router.attach('/', [route, ...])No docs description yet.
- @param
messageresponse message.
Possible errors:
CustomError(), UnauthorizedError(), NotFoundError(), ConflictError(), ValidationError(), ForbiddenError()
Example:
throw new ConflictError('User is already exist.')@11z/express build everything Api (Application program interface) lighter, easier and maintainable.