Giải pháp chuyển đổi số trọn gói cho doanh nghiệp Việt

Xây dựng file model car.js - Xây dựng API backend quản lý Car bằng server nodejs

Xây dựng API backend quản lý Car bằng server nodejs

← Toàn bộ tài liệu


Bước 8.1: Xây dựng file model car.js

Bài 10/21 Xem dạng sách

Tại thư mục admin/apps/ecommerce/models

Tên file: car.js

Nội dung file:

var modelbackenditem = require(`${path_root}/lib/mvc/models/modelbackenditem`);
var model = require(`${path_root}/lib/mvc/models/model`);
const factory = require(`${path_root}/lib/Factory.js`);
class car extends modelbackenditem {
tableName() {
return "cars";
}
formXmlName() {
return "car";
}
async getItem(req, res, next,id) {
const input = factory.getInput(req);
if(typeof id==="undefined"){
id=input.getString("id","");
}
const car= await super.getItem(req, res, next,id);
car.image=await this.getImageByCarId(req, res, next,car._id.toString());
return car
}
async getImageByCarId(req, res, next,img_parent_id) {
const db = req.app.db;
const item = await db.images.findOne(
{
img_parent_id: img_parent_id.toString(),
img_type:"car-image"
}
);
if (!item) {
// If API request, return json
if (req.apiAuthenticated) {
res.status(400).json({message: 'Item not found'});
return null;
}
req.session.message = 'Item not found';
req.session.messageType = 'danger';
return null;
}

return item;
}
async save(data) {
let car=await super.save(data);
const imageModel=model.getInstance('image',0,req, res, next);
let current_image=await imageModel.getImageBycarId(this.req, this.res, this.next,car._id);
let car_id=car._id;
if (!this.req.files || Object.keys(this.req.files).length === 0) {

}

if(this.req.files !== null && typeof this.req.files.image !=="undefined") {
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let image = this.req.files.image;
// Use the mv() method to place the file somewhere on your server
let img_path = `backend/images/${image.name}`;
const modelImage = model.getInstance("image", 1, this.req, this.res, this.next);
image.mv(`${path_root}/public/${img_path}`, async function (err) {
if (err) {
//return this.res.status(500).send(err);
}
});
let data_image = {
"_id": "",
"img_id": "",
"img_parent_id": car_id,
"img_type": "",
"img_path": img_path,
"Img_width": "",
"img_height": "",
"img_desc": "",
};
if(typeof current_image!=="undefined"){
data_image['_id']=current_image._id
}
data_image = await modelImage.save(data_image);
car.default_photo = data_image;
}
return car;
}


}
module.exports = car;

Sơ đồ quan hệ các bảng

Table Name: {{table.name}}
Num Name Type
{{field_index+1}}
{{field.name}} {{field.type}}

Hỏi đáp

Gửi với tên {{comment_full_name}}

Chưa có câu hỏi nào cho bài này.

Zalo 0936.006.058 Hotline 0936.006.058