utils.service.ts 799 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { Injectable } from '@nestjs/common';
  2. import crypto from 'crypto';
  3. import type { FastifyRequest } from 'fastify';
  4. import Qqwry from 'lib-qqwry';
  5. import { isArray } from 'lodash';
  6. @Injectable()
  7. export class UtilsService {
  8. private qqwry = new Qqwry(true);
  9. getRealIp(req: FastifyRequest) {
  10. let clientIp = req.headers['x-forwarded-for'] || req.ip;
  11. if (isArray(clientIp)) {
  12. clientIp = clientIp[0];
  13. }
  14. clientIp = clientIp.split(',')[0];
  15. return clientIp;
  16. }
  17. getIpRegion(ip: string) {
  18. if (ip == null) {
  19. return;
  20. }
  21. try {
  22. const result = this.qqwry.searchIP(ip);
  23. return result.Country;
  24. } catch (err) {
  25. return '未知地区';
  26. }
  27. }
  28. getMd5(str: string) {
  29. return crypto.createHash('md5').update(str).digest('hex');
  30. }
  31. }