import { Config , Provide , Scope , ScopeEnum } from '@midwayjs/decorator' ; import { Context } from 'egg' ; import * as CryptoJS from 'crypto-js' ; import { customAlphabet , nanoid } from 'nanoid' ; import ErrorConstants from './error_constants' ; import * as JsonWebToken from 'jsonwebtoken' ; import { ResOp } from '../interface' ; export function res ( op ? ) { return { data : op ?. data ?? null , code : op ?. code ?? 200 , message : op ?. code ? getErrorMessageByCode ( op ! . code ) || op ?. message || 'unknown error' : op ?. message || 'success' , } ; } export function resByPage < V > ( list , total , page , size ) { return res ( { data : { list , pagination : { total , page , size , } , } , } ) ; } /**
 * 根据code获取错误信息
 */ export function getErrorMessageByCode ( code ) { return ErrorConstants [ code ] ; } @ Provide ( ) @ Scope ( ScopeEnum . Singleton ) export class Utils { @ Config ( 'jwt' ) jwt ; /**
     * 获取请求IP
     */ getReqIP ( ctx ) { const req = ctx . req ; return ( req . headers [ 'x-forwarded-for' ] || req . connection . remoteAddress || req . socket . remoteAddress || req . connection . socket . remoteAddress ) . replace ( '::ffff:' , '' ) ; } /**
     * AES加密
     */ aesEncrypt ( msg , secret ) { return CryptoJS . AES . encrypt ( msg , secret ) . toString ( ) ; } /**
     * AES解密
     */ aesDecrypt ( encrypted , secret ) { return CryptoJS . AES . decrypt ( encrypted , secret ) . toString ( CryptoJS . enc . Utf8 ) ; } /**
     * md5加密
     */ md5 ( msg ) { return CryptoJS . MD5 ( msg ) . toString ( ) ; } /**
     * 生成一个UUID
     */ generateUUID ( ) { return nanoid ( ) ; } /**
     * 生成一个随机的值
     */ generateRandomValue ( length , placeholder = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM' ) { const customNanoid = customAlphabet ( placeholder , length ) ; return customNanoid ( ) ; } /**
     * JsonWebToken Sign
     * https://github.com/auth0/node-jsonwebtoken
     */ jwtSign ( sign , options ? ) { return JsonWebToken . sign ( sign , this . jwt . secret , options ) ; } /**
     * JsonWebToken Verify
     * https://github.com/auth0/node-jsonwebtoken
     */ jwtVerify ( token , options ? ) { return JsonWebToken . verify ( token , this . jwt . secret , options ) ; } }