'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 }) { assert(name, '名称不存在'); assert(path, '路径不存在'); const { Files: model } = this.ctx.model; const createAt = moment().format('x'); try { await model.create({ name, path, createAt }); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error({ errcode: -2001, errmsg: '添加失败' }); } } async update({ name, path, id }) { assert(id, 'id不存在'); const { Files: model } = this.ctx.model; try { await model.findByIdAndUpdate(id, { name, path }); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error({ errcode: -2001, errmsg: '修改失败' }); } } async del({ id }) { assert(id, 'id不存在'); const { Files: model } = this.ctx.model; try { // 获取文件路径 const files = await model.findById(id); const filepath = `${files.path}`; // 开始删除文件 await fsPromises.rmdir(filepath); await model.findOneAndDelete(id); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error({ errcode: -2001, errmsg: '删除失败' }); } } async query({ skip, limit, filter }) { const { Files: model } = this.ctx.model; try { let res; if (skip && limit) { res = await model.find(filter).skip(skip * limit).limit(limit); } else { res = await model.find(filter); } return { errmsg: '', errcode: 0, data: res }; } catch (error) { throw new Error({ errcode: -2001, errmsg: '查询失败' }); } } async upload({ type }) { try { const stream = await this.ctx.getFileStream(); // 创建文件存储名称 const filename = stream.filename; const index = filename.indexOf('.'); const fileType = filename.slice(index, filename.length); const uuid = uuidv1(); const paths = path.join(this.app.baseDir, `/app/public/${type === 'files' ? 'files' : 'resource'}/${uuid}${fileType}`); // 存储 const remoteFileStream = fs.createWriteStream(paths); stream.pipe(remoteFileStream); return { errmsg: '', errcode: 0, data: { name: filename, path: paths } }; } catch (error) { throw new Error({ errcode: -2001, errmsg: '上传失败' }); } } } module.exports = FilesService;