user.js 2.19 KB
'use strict';
const mysqlCli = global.yoho.utils.mysqlCli;

const TABLE_USER = 'user';

class UserModel extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
    }

    getUser(mobile) {
        return mysqlCli.query(`select * from ${TABLE_USER}
            where user_phone=:mobile`, {
                mobile
            });
    }

    createUser({name, mobile, avatar}) {
        name = name || '';
        mobile = mobile || '';
        avatar = avatar || '';

        return mysqlCli.insert(
            `insert into ${TABLE_USER} 
            (user_phone, user_name, user_avatar) values (:mobile, :name, :avatar);`, {
                name,
                mobile,
                avatar
            });
    }

    /**
     * 创建微信用户
     * @param union_id
     * @param name
     * @param avatar
     * @param is_wechat
     * @returns {*}
     */
    createWechatUser(union_id, name, avatar, is_wechat) {
        let params = {
            mobile: '0',
            name: name,
            avatar: avatar,
            union_id: union_id,
            is_wechat: is_wechat || 1
        };

        let sqlStr = `INSERT INTO ${TABLE_USER}
            (user_phone, user_name, user_avatar, union_id, is_wechat_user) VALUES 
            (:mobile, :name, :avatar, :union_id, :is_wechat);`;

        return mysqlCli.insert(sqlStr, params);
    }

    /**
     * 根据union_id获取用户信息
     * @param union_id
     * @returns {*}
     */
    getWechatUser(union_id) {
        let sqlStr = `SELECT * FROM ${TABLE_USER} 
                    WHERE union_id = :union_id 
                    AND is_wechat_user = 1;`;

        return mysqlCli.query(sqlStr, {
            union_id
        });
    }

    /**
     * 根据union_id更新用户昵称和头像
     * @param union_id
     * @param name
     * @param avatar
     * @returns {*}
     */
    modifyWechatUser(union_id, name, avatar) {
        let sqlStr = `UPDATE ${TABLE_USER} SET 
                      user_name = :name, user_avatar = :avatar 
                      WHERE union_id = :union_id;`;

        return mysqlCli.update(sqlStr, {
            name,
            avatar,
            union_id
        });
    }

}

module.exports = UserModel;