create-api-server.js 1.83 KB
const api = global.yoho.API;
const service = global.yoho.ServiceAPI;
const checkParams = require('../../utils/check-params');
const apiMaps = require('../../config/api-map');
const _ = require('lodash');

const NOT_FOUND_API_MAP = {
    code: 400,
    message: '未找到对应的接口'
};
const checkApiMap = url => {
    return apiMaps[url] ? apiMaps[url] : void 0;
};
const request = async ({url, method, reqParams, context}) => {
    const apiInfo = checkApiMap(url);

    if (!apiInfo) {
        return Promise.reject(NOT_FOUND_API_MAP);
    }
    try {
        if (!apiInfo.service) {
            Object.assign(reqParams, {
                uid: context.user.uid || 0,
                method: apiInfo.api
            });
        }
        if (_.has(apiInfo, 'params.uid') &&
            apiInfo.params.uid.require !== false &&
            reqParams.uid === 0) { // 如果接口uid是必须的但是有没有传入uid则直接返回空对象
            return Promise.resolve({});
        }
        const params = checkParams.getParams(reqParams, apiInfo);
        const cache = method.toLowerCase() !== 'get' ? false : apiInfo.cache;

        if (apiInfo.service) {
            return await service.get(apiInfo.api, params, {
                cache: cache,
                code: 200
            });
        } else {
            return await api[method]('', params, {
                code: 200,
                cache: cache
            });
        }
    } catch (e) {
        return Promise.reject({
            code: 400,
            message: `create api:${e}`
        });
    }
};

export const createApi = context => {
    return {
        get(url, reqParams) {
            return request({url, method: 'get', reqParams, context});
        },
        post(url, reqParams) {
            return request({url, method: 'post', reqParams, context});
        }
    };
};