# Loopback tutorial
Chạy lệnh lb4 app và điền thông tin
Bỏ docker
Chạy lb4 model, tên Todo, thêm các field
id: string, bắt buộc, generate tự động
title: string, bắt buộc
description: string, không bắt buộc
isComplete: boolean, bắt buộc
deadline: date, không bắt buộc
Mở file todo.model.ts, thay đổi như sau:
```typescript
@model({
settings: {
mongodb: {
collection: 'todo'
}
}
})
// phần id
mongodb: {
dataType: 'ObjectId',
},
// những phần còn lại
mongodb: {
fieldName: 'description'
}
```
Chạy lb4 datasource, đặt tên db
* host: 127.0.0.1
* port: 27017
* db: list-todos
* Feature support: Yes
Thêm useFindAndModify, useCreateIndex, useUnifiedTopology vào datasource
Chạy lb4 repository
Chạy lb4 controller, đặt tên todo, Yes ở ommitted
Chạy npm i express, npm i --save-dev @types/express
Thêm file server.ts vào ./src
Nội dung 1:
```typescript
import express from 'express';
export class ExpressServer {
constructor() {
}
}
```
Nội dung 2:
```typescript
import express from 'express';
import http from 'http';
import {ApplicationConfig, ListTodosApplication} from './application';
export {ApplicationConfig};
export class ExpressServer {
public readonly app: express.Application;
public readonly lbApp: ListTodosApplication;
private server?: http.Server;
constructor(options: ApplicationConfig) {
this.app = express();
this.lbApp = new ListTodosApplication(options);
}
}
```
Thêm dòng này vào cuối constructor:
```typescript
this.app.use('/api', this.lbApp.requestHandler);
```
Chỉnh 2 dòng trong public/index.html
```htmlembedded
<h3>OpenAPI spec: <a href="/api/openapi.json">/openapi.json</a></h3>
<h3>API Explorer: <a href="/api/explorer">/explorer</a></h3>
```
??: Nullish Coalescing Operator
Nội dung 3
```typescript
async boot() {
await this.lbApp.boot();
}
public async start() {
await this.lbApp.start();
const port = this.lbApp.restServer.config.port ?? 3000;
const host = this.lbApp.restServer.config.host || '127.0.0.1';
this.server = this.app.listen(port, host);
await once(this.server, 'listening');
}
```
qua index.ts xóa chừa mỗi import dòng đầu, xóa ApplicationConfig trong dòng đầu
Thêm vào index.ts:
```typescript
export {ListTodosApplication, ApplicationConfig, ExpressServer};
export async function main(options: ApplicationConfig = {}) {
const server = new ExpressServer(options);
await server.boot();
await server.start();
console.log('Server is running!');
}
if (require.main === module) {
const config = {
rest: {
port: process.env.PORT ?? 3000,
host: process.env.HOST ?? 'localhost',
listenOnStart: false,
}
};
main(config)
.catch(err => console.log(err));
}
```
Xử lý custom response từ controller:
Thêm vào RequestContext, RestBindings từ @loopback/rest, {inject} từ @loopback/core
Thêm vào constructor:
@inject(RestBindings.Http.RESPONSE)
private requestContext: RequestContext
lấy response: this.requestContext.response