user-service.js 2.24 KB
/**
 * Created by TaoHuang on 2017/4/17.
 */

'use strict';

const _ = require('lodash');
const md5 = require('yoho-md5');
const Context = require('../common/context');
const rp = require('request-promise');
const Api = require('../common/api');
const apiDomain = global.yoho.apiDomain;
const config = global.yoho.config;

const regSession = '${0}=([^;]+);';

class UserService extends Context {
    constructor() {
        super();
        this.api = this.instance(Api);
    }
    login(account, password) {
        return this.api.post(apiDomain.erp.login, {
            account,
            password,
            platform: config.platform
        }).then(userInfo => {
            if (userInfo.code !== 200 || !userInfo.data.pid) {
                return Promise.reject({code: 500, message: '用户名密码错误'});
            }
            return userInfo.data;
        });
    }

    shopLogin(account, password) {
        return rp.post({
            url: apiDomain.shop.login,
            resolveWithFullResponse: true,
            formData: {
                user: account,
                password: password
            }
        }).then(response => {
            let sessId = '', sid = '';

            _.each(response.rawHeaders, header => {
                let sessIdMatched = header.match(new RegExp(regSession.replace('${0}', 'PHPSESSID')));
                let sidMatched = header.match(new RegExp(regSession.replace('${0}', 'connect\.sid')));

                if (sessIdMatched) {
                    sessId = sessIdMatched[1];
                }
                if (sidMatched) {
                    sid = sidMatched[1];
                }
            });
            return {
                PHPSESSID: sessId,
                'connect.sid': sid
            };
        });
    }

    getShops(pid) {
        return this.api.get(apiDomain.platform.queryShopsByAdminPid, {
            userId: pid
        }).then(result => {
            if (result.code === 200) {
                _.each(result.data, shop => {
                    shop.id = md5(shop.shopName);
                });
            }
            return result;
        });
    }

    profile(pid) {
        return this.instance(Api).get(apiDomain.shop.profile.url, {userId: pid});
    }
}


module.exports = UserService;