util.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const moment = require('moment');
  8. const nodemailer = require('nodemailer');
  9. class UtilService extends CrudService {
  10. async updatedate() {
  11. let date = new Date();
  12. date = moment(date).format('YYYY-MM-DD HH:mm:ss');
  13. return date;
  14. }
  15. async sendMail(email, subject, text, html) {
  16. const setting = await this.ctx.model.Setting.findOne();
  17. let user_email = this.ctx.app.config.user_email;
  18. let auth_code = this.ctx.app.config.auth_code;
  19. if (setting) {
  20. user_email = setting.user_email;
  21. auth_code = setting.auth_code;
  22. }
  23. const transporter = nodemailer.createTransport({
  24. host: 'smtp.exmail.qq.com',
  25. secureConnection: true,
  26. port: 465,
  27. auth: {
  28. user: user_email, // 账号
  29. pass: auth_code, // 授权码
  30. },
  31. });
  32. const mailOptions = {
  33. from: user_email, // 发送者,与上面的user一致
  34. to: email, // 接收者,可以同时发送多个,以逗号隔开
  35. subject, // 标题
  36. text, // 文本
  37. html,
  38. };
  39. try {
  40. await transporter.sendMail(mailOptions);
  41. return true;
  42. } catch (err) {
  43. return false;
  44. }
  45. }
  46. async findone({ modelname }, data) {
  47. // 查询单条
  48. const _model = _.capitalize(modelname);
  49. const res = await this.ctx.model[_model].findOne({ ...data });
  50. return res;
  51. }
  52. async findbyids({ modelname }, { data }) {
  53. // 共通批量查询方法
  54. const _model = _.capitalize(modelname);
  55. const res = [];
  56. for (const elm of data) {
  57. const result = await this.ctx.model[_model].findById(elm);
  58. res.push(result);
  59. }
  60. return res;
  61. }
  62. async findmodel({ modelname }) {
  63. const _model = _.capitalize(modelname);
  64. const data = this.ctx.model[_model].prototype.schema.obj;
  65. return data;
  66. }
  67. }
  68. module.exports = UtilService;