npm i express-lite-router
import {Router} from "express-lite-router";
import express, {Application} from "express";
import mariadb from "mariadb";
const router = Router({
router: express.Router(),
dir: 'src/backend',
context: {
pool: mariadb.createPool({
host: 'mydb.com',
user: 'myUser',
password: 'myPassword',
connectionLimit: 5
})
}
});
router.get('/', 'Home/HomeController@index');
const app: Application = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(router.express());
app.listen(3000, () => console.log('Development server http://localhost:3000 started'));
Your controller must be extended from 'Controller'
import {Controller} from "express-lite-router";
import Model from "@backend/Home/HomeModel";
export default class HomeController extends Controller {
private model: Model;
public async init() {
this.model = await this.$create(Model, 1);
}
public async index() {
try {
return this.success({rows: await this.model.select()});
} catch (e) {
return this.error(e);
}
}
}
Your model must be extended from 'Model'
import {Model} from "express-lite-router";
import {Pool} from "mariadb";
export default class HomeModel extends Model {
private id;
public constructor(id: number) {
super();
this.id = id;
}
public async init() {
console.log("Hello, I'm a webhook");
}
public async select() {
return await this.pool.query(`SELECT ${this.id} as val`);
}
private get pool(): Pool {
return this.$context.pool;
}
}
// OR http://localhost:3000/api?lang=ua
// OR { lang: 'ua' }
console.log(this.$lang); // 'ua'
console.log(this.request); // express Request
this.response; // express Response
const router = Router({
context: {
pool: mariadb.createPool({
host: 'mydb.com',
user: 'myUser',
password: 'myPassword',
connectionLimit: 5
})
}
});
console.log(this.$context); // { pool, request, response }
console.log(this.$lang); // 'en'
console.log(this.$l({"en":"Not found", "ua":"Не знайдено"})); // 'Not found'
this.model = await this.$create(Model, 1);
try {
return this.success(); // json
} catch (e) {
}
try {
} catch (e) {
return this.error(e); // json
}
try {
throw new ApiError('Not found', 404);
} catch (e) {
return this.error(e); // json
}