user.js 2.09 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
     * @param next
     */
    userInfo(req, res, next) {
        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.substr(7);
                    let avatar = 'http://img12.static.yhbimg.com/' +
                        'imserver/2016/11/17/11/02bc3c3de856432175c01d937342a1f2ce.jpg';

                    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
                            });
                        })
                        .catch(next);
                }
            })
            .catch(next);
    }
};

module.exports = userController;