helper.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import * as yaml from 'js-yaml';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as CryptoJS from 'crypto-js';
  5. import { IHelper } from 'egg';
  6. import { customAlphabet } from 'nanoid';
  7. import * as moment from 'moment';
  8. import * as jwt from 'jsonwebtoken';
  9. import { v4 as uuidv4 } from 'uuid';
  10. /**
  11. * 格式化时间
  12. */
  13. export const now = function() {
  14. return moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  15. };
  16. /**
  17. * 错误信息map
  18. */
  19. let errorMap = null;
  20. export default {
  21. /**
  22. * 获取请求IP
  23. */
  24. getReqIP(this: IHelper) {
  25. const req: any = this.ctx.req;
  26. return (req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
  27. req.connection.remoteAddress || // 判断 connection 的远程 IP
  28. req.socket.remoteAddress || // 判断后端的 socket 的 IP
  29. req.connection.socket.remoteAddress).replace('::ffff:', '');
  30. },
  31. /**
  32. * 根据code获取错误信息
  33. */
  34. getErrorMessageByCode(code: string) {
  35. if (!errorMap) {
  36. errorMap = yaml.safeLoad(fs.readFileSync(path.resolve(__dirname, '../../config/error_constants.yaml'), 'utf8'));
  37. }
  38. return errorMap![code];
  39. },
  40. /**
  41. * AES加密
  42. */
  43. aesEncrypt(this: IHelper, msg: string, secret: string) {
  44. return CryptoJS.AES.encrypt(msg, secret).toString();
  45. },
  46. /**
  47. * AES解密
  48. */
  49. aesDecrypt(this: IHelper, encrypted: string, secret: string) {
  50. return CryptoJS.AES.decrypt(encrypted, secret).toString(CryptoJS.enc.Utf8);
  51. },
  52. /**
  53. * md5加密
  54. */
  55. md5(msg: string) {
  56. return CryptoJS.MD5(msg).toString();
  57. },
  58. /**
  59. * 生成一个随机的值
  60. */
  61. generateRandomValue(length: number, placeholder = '1234567890qwertyuiopasdfghjklzxcvbnm') {
  62. const nanoid = customAlphabet(placeholder, length);
  63. return nanoid();
  64. },
  65. /**
  66. * 生成一个UUID
  67. */
  68. generateUUID() {
  69. return uuidv4();
  70. },
  71. /**
  72. * 获取当前时间
  73. */
  74. getDate() {
  75. return now();
  76. },
  77. /**
  78. * JsonWebToken Sign
  79. * https://github.com/auth0/node-jsonwebtoken
  80. */
  81. jwtSign(this: IHelper, sign: any, options?: any) {
  82. return jwt.sign(sign, this.config.jwt.secret, options);
  83. },
  84. /**
  85. * JsonWebToken Verify
  86. * https://github.com/auth0/node-jsonwebtoken
  87. */
  88. jwtVerify(this: IHelper, token: string, options?: any) {
  89. return jwt.verify(token, this.config.jwt.secret, options);
  90. },
  91. };