'use strict'; const Service = require('egg').Service; const assert = require('assert'); const moment = require('moment'); const { v1: uuidv1 } = require('uuid'); const fs = require('fs'); const path = require('path'); // const fsPromises = fs.promises; class FilesService extends Service { async create({ name, path, type }) { assert(name, '名称不存在'); assert(path, '路径不存在'); assert(type, '类型不存在'); const { Files: model } = this.ctx.model; const createAt = moment().format('YYYY-MM-DD HH:mm:ss'); try { await model.create({ name, path, type, createAt }); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error('添加失败'); } } async update({ name, path, id }) { assert(id, 'id不存在'); const { Files: model } = this.ctx.model; try { await model.findById(id).update({ name, path }); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error('修改失败'); } } async del({ id }) { assert(id, 'id不存在'); const { Files: model } = this.ctx.model; try { // 获取文件路径 const files = await model.findById(id); const filepath = `${this.app.config.filespath}${files.path}`; // 开始删除文件 fs.unlinkSync(path.join(filepath)); await model.findById(id).remove(); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error('删除失败'); } } async query({ skip, limit, type, name }) { assert(type, '类型不存在'); const filter = {}; filter.type = type; if (name) filter.name = name; const { Files: model } = this.ctx.model; try { const total = await model.find({ ...filter }); let res; if (skip && limit) { res = await model.find({ ...filter }).skip(Number(skip) * Number(limit)).limit(Number(limit)); } else { res = await model.find({ ...filter }); } return { errmsg: '', errcode: 0, data: res, total: total.length }; } catch (error) { throw new Error('查询失败'); } } async upload() { try { const stream = await this.ctx.getFileStream(); const type = stream.fields.type; // 创建文件存储名称 const filename = stream.filename; const index = filename.indexOf('.'); const fileType = filename.slice(index, filename.length); const uuid = uuidv1(); const filepath = `/filespath/${type}/${uuid}${fileType}`; const paths = path.join(`${this.app.config.filespath}${filepath}`); // const filepath = `/public/${type}/${uuid}${fileType}`; // const paths = path.join(this.app.baseDir, `/app${filepath}`); // 存储 const result = await new Promise((resolve, reject) => { const remoteFileStream = fs.createWriteStream(paths); stream.pipe(remoteFileStream); let errFlag; remoteFileStream.on('error', err => { errFlag = true; remoteFileStream.destroy(); reject(err); }); remoteFileStream.on('finish', async () => { if (errFlag) return; resolve(true); }); }); if (!result) { throw new Error('上传失败'); } await this.ctx.service.files.create({ name: filename, path: filepath, type }); return { errmsg: '', errcode: 0, data: { name: filename, path: filepath } }; } catch (error) { console.log(error, 'error'); throw new Error('上传失败'); } } } module.exports = FilesService;