koa-backend-server v0.5.7
Koa Backend Server
KBS, Koa Backend Server with TypeScript.
Version
WARNING: This project is currently in an UNSTABLE version.
WARNING: This project is currently in an UNSTABLE version.
WARNING: This project is currently in an UNSTABLE version.
Feature
- feat: support for creating cluster servers
Change log
0.5.6 => 0.5.7
- docs: update LICENSE
- perf: update author information
- perf: default in development mode
- perf: it is recommended to use code for configuration first
0.4.7 => 0.5.0
- perf: never use KoaBody in OPTIONS and HEAD method
- perf: provide more help information
- feat: support for using server.config.json(cover other) to configure KBS
- feat: use server.config.json instead of ormconfig.json
Installation
Koa Backend Server on NPM
npm i --save koa-backend-server
DO NOT install koa and other dependencies AGAIN!
Usage
See example:
Full config
It will create a HTTP server which is listening on port 8080.
import { Server } from 'koa-backend-server';
const server = new Server({
address: {
portocol: 'HTTP', // Optional, HTTP, HTTPS or HTTP2.
host: '0.0.0.0', // Optional, default to 0.0.0.0.
port: 8080, // Optional, default to 8080.
ssl: {cert: 'CERT', key: 'KEY'} // Required if portocol is HTTP2 or HTTPS.
},
database: { // If undefined, it will disable database connection
name: 'default',
type: 'mysql',
host: 'localhost',
port: 3306,
database: 'database',
username: 'username',
password: 'password',
synchronize: true, // auto generate database table (or document), but you may lost all data of this database
logging: true, // log all query statements
entities: ['somewhere/entity/**/*.entity.ts'] // your database table(entity)
},
router: { // If undefined, it will disable koa router.
paths: { // router paths
POST: {
'index': {
path: '/',
ware: async (c, next) => {
c.session.data = c.request.body;
c.body = {
status: Boolean(c.session),
data: c.session
};
await User.insert({
name: 'test',
password: 'password',
disable: false,
value: 100
});
await next();
}
}
}
},
static: { // Static files path.
path: 'test/html/'
},
version: 'v1' // API version, the prefix of all paths.
},
session: { // If undefined, it will disable redisession.
domain: 'your.domain',
httpOnly: true,
maxAge: 3600, // expire time, second
name: 'session.id', // cookie key name
redis: { // redis server
host: 'your.redis.address',
port: 6379
},
secert: ['your', 'secert', 'keys']
}
});
// Start listening.
server.listen();
Step by step
0. Know about the interface KBSConfig.
/** KBS config. */
export interface KBSConfig {
/** KBS address. */
address: KBSAddress;
/** KBS database connection, if undefined it will disable the typeorm connection. */
database?: KBSDatabase;
/** KBS router, if undefined it will disable the koa router. */
router?: KBSRouter;
/** KBS session, if undefined it will disable the koa session. */
session?: Options;
}
1. Set your address information.
Use KBSAddress to configure your address info.
const address: KBSAddress = { // optional, default to http://0.0.0.0:8080
portocol: 'HTTP', // optional, HTTP, HTTPS or HTTP2
host: '0.0.0.0', // optional, default to 0.0.0.0
port: 8080, // optional, default to 8080
ssl: {cert: 'CERT', key: 'KEY'} // required if portocol is HTTPS or HTTP2
};
Or use server.config.json to do this.
{
"address": {
"portocol": "HTTP",
"host": "0.0.0.0",
"port": 8080,
"ssl": {
"cert": "CERT content here if HTTP2/S",
"key": "KEY content here if HTTP2/S"
}
}
}
It will cover KBSDatabase config.
2. (Optional) Connect database via TypeORM.
Use KBSDatabase to create connection.
const database: KBSDatabase = { // If undefined, it will disable database connection
name: 'default',
type: 'mysql',
host: 'localhost',
port: 3306,
database: 'database',
username: 'username',
password: 'password',
synchronize: true, // auto generate database table (or document), but you may lost all data of this database
logging: true, // log all query statements
entities: ['somewhere/entity/**/*.entity.ts'] // your database table(entity)
};
Or use server.config.json to do this.
{
"database": {
"type": "mysql",
"host": "your.database.host",
"port": 3306,
"username": "username",
"password": "password",
"database": "database",
"synchronize": true,
"logging": true,
"entities": [
"test/entity/**/*.entity.ts"
],
"migrations": [],
"subscribers": []
}
}
It will cover KBSDatabase config.
3. (Optional but important) Set router paths and API version.
Here is the router path interface.
interface RouterPaths {
[index: string]: {
path: string | RegExp | (string | RegExp)[];
ware: any;
cors?: CORS;
withoutPrefix: boolean;
};
}
And the post path looks like this.
// post/index.ts
import { AMiddleware, now, RouterPaths } from 'koa-backend-server';
import { User } from '../entity';
import test from './test';
const index: AMiddleware = async (c, next) => {
const request = c.request.body;
const insert = await User.insert({ name: now(), password: 'any' });
const data = await User.find();
c.session.user = data;
c.body = {
status: true,
data
};
await next();
};
export const postPaths: RouterPaths = {
'/test': {
path: '/test',
ware: test,
cors: {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': ['POST', 'OPTIONS', 'GET'],
'Access-Control-Allow-Origin': '*'
}
},
'all': {
path: /\/.*/,
ware: index,
withoutPrefix: true
}
};
export default postPaths;
Don't forget to define the KBSRouter.
const router: KBSRouter = { // if undefined, it will disable koa router
paths: { // router paths
POST: postPaths
},
static: { // static files dir, without version prefix
path: 'static/files/dir',
options: { /* Some options. */ }
},
version: 'v1' // API version, the prefix of all paths
};
The same way to use server.config.json to do this.
4. (Optional) Config your session options.
Use KBSSession to do this.
const session: KBSSession = { // If undefined, it will disable redisession.
domain: 'your.domain',
httpOnly: true,
maxAge: 3600, // expire time, second
name: 'session.id', // cookie key name
redis: { // redis server
host: 'your.redis.address',
port: 6379
},
secert: ['your', 'secert', 'keys']
};
The same way to use server.config.json to do this.
5. And now, it looks like this.
Enter point: test/index.ts
import { KBSAddress, KBSDatabase, KBSRouter, KBSSession, Server } from 'koa-backend-server';
import postPaths from './post';
const address: KBSAddress = { // optional, default to http://0.0.0.0:8080
portocol: 'HTTP', // optional, HTTP, HTTPS or HTTP2
host: '0.0.0.0', // optional, default to 0.0.0.0
port: 8080, // optional, default to 8080
ssl: {cert: 'CERT', key: 'KEY'} // required if portocol is HTTPS or HTTP2
};
const database: KBSDatabase = { // If undefined, it will disable database connection
name: 'default',
type: 'mysql',
host: 'localhost',
port: 3306,
database: 'database',
username: 'username',
password: 'password',
synchronize: true, // auto generate database table (or document), but you may lost all data of this database
logging: true, // log all query statements
entities: ['somewhere/entity/**/*.entity.ts'] // your database table(entity)
};
const router: KBSRouter = { // if undefined, it will disable koa router
paths: { // router paths
POST: postPaths
},
static: { // static files dir, without version prefix
path: 'static/files/dir',
options: { /* Some options. */ }
},
version: 'v1' // API version, the prefix of all paths
};
const session: KBSSession = { // If undefined, it will disable redisession.
domain: 'your.domain',
httpOnly: true,
maxAge: 3600, // expire time, second
name: 'session.id', // cookie key name
redis: { // redis server
host: 'your.redis.address',
port: 6379
},
secert: ['your', 'secert', 'keys']
};
const server: Server = new Server({address, database, router, session});
server.listen();
See the Work tree.
┏━ src/
┃ ┣━ entity/
┃ ┃ ┣━ index.ts
┃ ┃ ┗━ user.entity.ts
┃ ┣━ post/
┃ ┃ ┃━ index.ts
┃ ┃ ┗━ test.ts
┃ ┗━ index.ts
┣━ .gitignore
┣━ LICENSE
┣━ server.config.json
┣━ package-lock.json
┣━ package.json
┣━ README.md
┣━ tsconfig.json
┗━ tslint.json
Advanced usage
Use your own middlewares.
server.use(middlewareA, middlewareB, middlewareC, /* ... */);
Some others
Emmm, maybe later?
Thanks
License
Author
Devin Don, Email, Github, My Home Page(Under construction).
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago