files.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const assert = require('assert');
  4. const moment = require('moment');
  5. const { v1: uuidv1 } = require('uuid');
  6. const fs = require('fs');
  7. const path = require('path');
  8. const fsPromises = fs.promises;
  9. class FilesService extends Service {
  10. async create({ name, path }) {
  11. assert(name, '名称不存在');
  12. assert(path, '路径不存在');
  13. const { Files: model } = this.ctx.model;
  14. const createAt = moment().format('x');
  15. try {
  16. await model.create({ name, path, createAt });
  17. return { errmsg: '', errcode: 0 };
  18. } catch (error) {
  19. throw new Error({ errcode: -2001, errmsg: '添加失败' });
  20. }
  21. }
  22. async update({ name, path, id }) {
  23. assert(id, 'id不存在');
  24. const { Files: model } = this.ctx.model;
  25. try {
  26. await model.findByIdAndUpdate(id, { name, path });
  27. return { errmsg: '', errcode: 0 };
  28. } catch (error) {
  29. throw new Error({ errcode: -2001, errmsg: '修改失败' });
  30. }
  31. }
  32. async del({ id }) {
  33. assert(id, 'id不存在');
  34. const { Files: model } = this.ctx.model;
  35. try {
  36. // 获取文件路径
  37. const files = await model.findById(id);
  38. const filepath = `${files.path}`;
  39. // 开始删除文件
  40. await fsPromises.rmdir(filepath);
  41. await model.findOneAndDelete(id);
  42. return { errmsg: '', errcode: 0 };
  43. } catch (error) {
  44. throw new Error({ errcode: -2001, errmsg: '删除失败' });
  45. }
  46. }
  47. async query({ skip, limit, filter }) {
  48. const { Files: model } = this.ctx.model;
  49. try {
  50. let res;
  51. if (skip && limit) {
  52. res = await model.find(filter).skip(skip * limit).limit(limit);
  53. } else {
  54. res = await model.find(filter);
  55. }
  56. return { errmsg: '', errcode: 0, data: res };
  57. } catch (error) {
  58. throw new Error({ errcode: -2001, errmsg: '查询失败' });
  59. }
  60. }
  61. async upload({ type }) {
  62. try {
  63. const stream = await this.ctx.getFileStream();
  64. // 创建文件存储名称
  65. const filename = stream.filename;
  66. const index = filename.indexOf('.');
  67. const fileType = filename.slice(index, filename.length);
  68. const uuid = uuidv1();
  69. const paths = path.join(this.app.baseDir, `/app/public/${type === 'files' ? 'files' : 'resource'}/${uuid}${fileType}`);
  70. // 存储
  71. const remoteFileStream = fs.createWriteStream(paths);
  72. stream.pipe(remoteFileStream);
  73. return { errmsg: '', errcode: 0, data: { name: filename, path: paths } };
  74. } catch (error) {
  75. throw new Error({ errcode: -2001, errmsg: '上传失败' });
  76. }
  77. }
  78. }
  79. module.exports = FilesService;