user.js 2.05 KB
/**
 * 用户controller
 * @author: leo <qi.li@yoho.cn>
 * @date: 2017/06/26
 */
'use strict';
const _ = require('lodash');
const UserModel = require('../models/user');

const GET_USER_INFO_SUCCESS = '获取用户信息成功';

const userController = {
    /**
     * 获取用户信息
     * @param req
     * @param res
     */
    userInfo(req, res) {
        const mobile = _.get(req.session, 'smsSend.mobile', '');

        req.ctx(UserModel).getUser(mobile)
            .then(result => {
                let userInfo = {};

                if (result.length) {
                    let user = result[0];

                    // 用户ID
                    _.set(req.session, 'user.id', user.id);

                    res.json({
                        code: 200,
                        data: {
                            id: user.id,
                            name: user.user_name,
                            mobile: user.user_phone,
                            avatar: user.user_avatar
                        },
                        message: GET_USER_INFO_SUCCESS
                    });
                } else {
                    let name = mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
                    let avatar = 'http://img12.static.yhbimg.com/' +
                        'imserver/2016/11/17/11/02bc3c3de856432175c01d937342a1f2ce.jpg'; // TODO TO BE REPLACED

                    userInfo = {
                        name,
                        avatar,
                        mobile
                    };

                    req.ctx(UserModel).createUser(userInfo)
                        .then((id) => {

                            // 用户ID
                            _.set(req.session, 'user.id', id);

                            res.json({
                                code: 200,
                                data: _.assign(userInfo, {id}),
                                message: GET_USER_INFO_SUCCESS
                            });
                        });
                }
            });
    }
};

module.exports = userController;