@11z/express v1.24.0
@11z/express
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.
Feature ✨ What so special about @11z/express?
- Error handler such as 404 exception and global exception ✔
- Catch async error on all routes ✔
OOP
andMVC
based routing or functionality are also supported ✔- Typescript support out of the box.
cjs
,umd
are also supported. ✔ - Route validation ✔
- Lighter, easier and maintainable ✔
👉 Some of these features are optional.
Table of contents
Example
Note: You don’t need to install the express library. everything is included.
Start the server:
./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'))
Register route:
./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'))
With decorator:
./ex.sev.ts
See more about @11z/core.
import { Injectable } from '@11z/core'
@Injectable()
export class ExampleService {
public helloWorld(): string {
return 'Hello world!'
}
}
./ex.api.ts
import { Api, Get } from '@11z/express'
import { ExampleService } from './ex.sev.ts'
@Api()
export class ExampleApi {
constructor(private readonly exampleService: ExampleService) {}
@Get()
public helloWorld(): string {
return this.exampleService.helloWorld()
}
}
./ex.rou.ts
import express, { Route } from '@11z/express'
import { ExampleApi } from './cat.api.ts'
@Route([ExampleApi], { router: express.Router() })
export class ExampleRoute {}
Attach and register decorated route:
./server.ts
import express, { Router } from '@11z/express'
import { ExampleRoute } from './ex.ro.ts'
import { connect } from './database' // this could be mongo, sql, etc.
// Initialize express.
const app = express()
// Router instance.
const router = new Router({ initial: app })
// Attach and register decorated route.
router.attach('/api/v1', [ExampleRoute])
async function __main__() {
// TODO: Connect to database.
await connect({ uri: 'DB_URI' })
// Listen for connections.
app.listen(4000, () => console.log('Server is up! visit: http://localhost:4000'))
}
// Execute main.
__main__()
Installation
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.
Apis
We provide all the Apis that you will need to create a flexible and maintainable application.
@Api
A class defined with methods for handling one or more requests.
- @param
url
url path.
Example:
import { Api } from '@11z/express'
@Api()
export class ExampleApi {}
@Method
A specific endpoint for HTTP requests.
- @param
method
http method type. - @param
url
url path. - @param
status
status code.
Possible methods:
@Get(), @Post(), @Put(), @Patch(), @Delete()
Example:
import { Get } from '@11z/express'
export class ExampleApi {
@Get()
public helloWorld(): string {
return 'hello world!'
}
}
@Middleware
A function which is called before the route handler.
- @param
mids
execute 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 {}
@Params
A named URL segments that are used to capture the values specified at their position in the URL.
- @param
name
request 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 => req.body
return 'hello world!'
}
}
@Validation
Validation middleware. A function which is called before the route handler.
- @param
schema
schema object.
Supported library: zod
Note: With some libraries besides
zod
can 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!'
}
}
@Route
No docs description yet.
- @param
Apis
api handlers. - @param
routeOptions
route options.
Example:
import express, { Route } from '@11z/express'
@Route([], { router: express.Router() })
export class ExampleRoute {}
Customize
You can customize some Apis according to your needs.
Middleware
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('User unauthorized.')
}
}
])
// Example usage:
export class ExampleApi {
@Authenticated()
public helloWorld(): string {
return 'hello world!'
}
}
Method
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!'
}
}
Errors
Customize response
error.
Example:
./errors.err.ts
import { CustomError } from '@11z/express'
export class BadRequestError extends CustomError {
public readonly status = 400
public readonly error = 'BAD_REQUEST'
constructor(public readonly message: string) {
super(message)
Object.setPrototypeOf(this, BadRequestError.prototype)
}
}
// Example usage:
throw new BadRequestError('Any message.')
Router
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({ initial: app })
// Attach and register decorated route.
router.attach('/', [route, ...])
Exception
No docs description yet.
- @param
message
response message.
Possible errors:
CustomError(), UnauthorizedError(), NotFoundError(), ConflictError(), ValidationError(), ForbiddenError()
Example:
throw new ConflictError('User is already exist.')
The end
@11z/express build everything Api (Application program interface) lighter, easier and maintainable.
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago