cool 框架 node 后端封装三方Api post请求函数

1.需求

现在一些数据源 ,需要从三方地址拿到一些数据 比如说电影列表 信息了 影院列表信息了 等一些展示的数据,但是人家这种东西 害需要使用 appkey appserect 这种验签

这种需求 你前端调用接口是直接调用不了的 因为需要用到验签 需要后端接口转接一下 前端再去调用接口

复制代码
import { Body, Config, Provide } from '@midwayjs/decorator';
import { Inject } from '@midwayjs/decorator';
import { BusinessStudentEntity } from '../entity/student';
import { BusinessUserEntity } from '../entity/user';
import { BusinessBaseConfigEntity } from '../entity/base/config';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

import { BaseService } from '@cool-midway/core';
import * as request from 'request';
import * as _ from 'lodash';
import * as crypto from 'crypto';
import { Context } from '@midwayjs/koa';

/**
 * http请求封装
 */
@Provide()
export class BussinessRequestService extends BaseService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(BusinessStudentEntity)
  businessStudentEntity: Repository<BusinessStudentEntity>;

  @InjectEntityModel(BusinessBaseConfigEntity)
  businessBaseConfigEntity: Repository<BusinessBaseConfigEntity>;

  @InjectEntityModel(BusinessUserEntity)
  businessUserEntity: Repository<BusinessUserEntity>;

  @Config('module.business')
  coolConfig;

  /**
   * post
   */
  async post(url, data = {}) {
    const { userId } = this.ctx.clientInfo;
    //学员信息
    const studentInfo = await this.businessStudentEntity.findOneBy({
      id: userId,
    });
    //对应 导员信息
    const adminInfo = await this.businessBaseConfigEntity.findOneBy({
      userId: String(studentInfo?.userId),
    });
    const requestConfig = this.coolConfig.request;
    let time = new Date().getTime();
    let pararm = {};
    pararm['appId'] = adminInfo.liangPiaoAppId;
    pararm['timestamp'] = time;
    let sign = this.generateSignature(
      pararm,
      data,
      adminInfo.liangPiaoSecret,
      adminInfo.liangPiaoAppId
    );
    return new Promise((resolve, reject) => {
      var option = {
        url:
          requestConfig.base_url +
          url +
          `?appId=${adminInfo.liangPiaoAppId}&sign=${sign}&timestamp=${time}`,
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'content-type': 'application/json',
        },
        body: data,
      };
      request(option, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          const { state, data } = body;
          if (state === 200) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  /**
   * get
   */
  // get(url, params = {}) {
  //   const requestConfig = this.mangoConfig.request;
  //   params['appId'] = requestConfig.appKey;
  //   params['timestamp'] = new Date().getTime();
  //   params['sign'] = this.generateSignature(
  //     params,
  //     requestConfig.appSecret,
  //     requestConfig.appKey,
  //     params['timestamp']
  //   );

  //   return new Promise((resolve, reject) => {
  //     var option = {
  //       url: requestConfig.base_url + url,
  //       method: 'GET',
  //       timeout: 30000,
  //       qs: params,
  //     };
  //     request(option, function (error, response, body) {
  //       if (!error && response.statusCode == 200) {
  //         const { code, data } = body;
  //         if (code === 1) {
  //           resolve(data);
  //         } else {
  //           reject(body);
  //         }
  //       } else {
  //         reject(error); // 返回错误信息
  //       }
  //     });
  //   });
  // }

  //计算签名
  generateSignature(params, body, secretKey, keys) {
    const joinedParams = this.joinRequestParams(params, body, secretKey, keys);
    const md5Hash = crypto
      .createHash('md5')
      .update(joinedParams)
      .digest('hex')
      .toUpperCase();

    return md5Hash;
  }
  //计算签名
  joinRequestParams(params, body, secretKey, keys) {
    const sb = [secretKey]; // 前面加上 secretKey
    const sortedParams = Object.keys(params)
      .filter(key => key !== 'sign' && params[key]) // 过滤掉不需要的键
      .sort(); // 对键进行排序

    for (const key of sortedParams) {
      sb.push(key + params[key]);
    }
    sb.push(JSON.stringify(body));
    sb.push(secretKey); // 最后加上 secretKey

    return sb.join('');
  }
}

当然一般 这种三方API 都有人家规定的验签规则 让你 写什么样的格式 拼接成什么样的格式

得看实际的需求 我这里主要介绍的是 post 请求的封装 (在jsNode 中书写后端接口) 是需要引入request 插件

相关推荐
跟着珅聪学java4 小时前
js编写中文转unicode 教程
前端·javascript·数据库
英俊潇洒美少年5 小时前
Vue3 深入响应式系统
前端·javascript·vue.js
颜酱5 小时前
回溯算法实战练习(3)
javascript·后端·算法
英俊潇洒美少年6 小时前
React 最核心 3 大底层原理:Fiber + Diff + 事件系统
前端·react.js·前端框架
我命由我123456 小时前
React Router 6 - 概述、基础路由、重定向、NavLink、路由表
前端·javascript·react.js·前端框架·ecmascript·html5·js
yaaakaaang6 小时前
(四)前端,如此简单!---Promise
前端·javascript
aini_lovee7 小时前
C# 实现邮件发送源码(支持附件)
开发语言·javascript·c#
英俊潇洒美少年7 小时前
js 进程与线程的讲解
javascript
Debug 熊猫8 小时前
豆包【实时通话】模型返回对话电音问题【已解决】
状态模式
dleei8 小时前
彻底淘汰老旧 SVG 插件:unplugin-icons 与 Tailwind CSS v4 自定义图标最佳实践
前端·程序员·前端框架