wechat,wechat-api,mongoose,winston等的使用

2021-02-16 14:16

阅读:478

标签:ons   token   middle   try   自动删除   ack   win   callback   mongodb   

目录:

技术分享图片

app.js

const express = require(express);
const app = express();
const wechat = require(wechat);
const config = require(./conf/config);
require(./db/mongo);
const userService = require(./service/userService);
const locationService = require(./service/locationService);
const logger = require(./util/logger);

app.use(config.path,wechat(config.wechat).text(function(message, req, res, next){
    logger.info(文本信息: + JSON.stringify(message));
    if(message.Content == 1){
        res.reply(kkkkkkkkkkkkkkkdkdkddkkdk);
    }
}).event(function(message, req, res, next){
    logger.info(事件消息: + JSON.stringify(message));
    if(message.Event === LOCATION){
        userService.addUser(message.FromUserName, function(err, user){
            if(err) logger.error(LOCATION saveOrUpdateUser error: %s, err)
            locationService.save(message,function(err, location){
                logger.info(location is : %s, location)
                res.reply({type: text, content: location});
                // res.reply(‘‘);
            })
        })
    }else if(message.Event === subscribe){
        res.reply(Welcome to subscribe!)
    }
})
.middlewarify());

const server = app.listen(18080, () => console.log(port is %s,server.address().port));

config.js

const config = {
    mongo: {
        connectStr: mongodb://user:123456@47.52.199.163:27017/test
    },
    wechat: {
        token: maoriaty1,
        appid: wx1af02f9490ff3e98,
        encodingAESKey: ‘‘,
        checkSignature: false
    },
    appSecret: 92bd3a03d76da03abba6b7d1c25c23a7,
    path: /wxService,
    logStdout: true //是否禁止输出debug日志
}

module.exports = config;

mongo.js

const config = require(../conf/config);
const mongoose = require(mongoose);

module.exports = (function(){
    mongoose.connect(config.mongo.connectStr, {auto_reconnect: true, native_parser: true}, function() {
        console.log(mongodb connected);
    })
    mongoose.set(debug, false);
    connection = mongoose.connection;
    connection.on(error, function(err) {
        console.log(new Date() + connect error : + err);
    });
    connection.on(close, function(){
        console.log(new Date() + connection close retry connect);
    });
    return connection;
})();

locationModel.js

const mongoose = require(mongoose);
const Schema = require(mongoose).Schema;

const location = new Schema({
    openId: {type: String, required: true},
    loc: {type: [Number], required: true, index: 2dsphere, sparse: true},
    precision: {type: Number, required: true, default: 0},
    createTime: {type: Date, required: true, default: Date.now},
    __v: {type: Number, select: false}
},{collection: location});

module.exports = locationModel = mongoose.model(location, location);

userModel.js

const mongoose = require(mongoose);
const Schema = require(mongoose).Schema;

const sexStates = [0, 2, 3]; //0-未知,1-男,2-女
const User = new Schema({
    openId: {type: String, unique: true, required: true, index: true},
    nickname: {type: String},
    sex: {type: Number, enum: sexStates},
    birthday: {type: Date},
    astroId: {type: String},
    province: {type: String, trim: true},
    city: {type: String, trim: true},
    conuntry: {type: String, trim: true},
    headimgurl: {type: String},
    privilege: {type: Array},
    createTime: {type: Date, default: Date.now, require: true},
    lastUpdateTime: {type: Date, default: Date.now, require: true},
    __v: {type: Number, select: false}
},{collection: user});

module.exports = userModel = mongoose.model(user, User);

locationService.js

const locationModel = require(../model/locationModel)

exports.save = function(message, callback){
    let location = new locationModel({
        openId: message.FromUserName,
        loc: [message.Longitude, message.Latitude],
        precision: message.Precision,
        createTime: new Date(parseInt(message.CreateTime) * 1000)
    })
    location.save(function(err, loc){
        if(err) console.log(save location error : %s, err)
        if(callback && callback instanceof Function){
            callback(err, loc)
        }
    })
}

userService.js

const config = require(../conf/config);
const userModel = require(../model/userModel);
const wechatApi = require(../util/wechatApi);
const API = wechatApi.API;

exports.addUser = function(openId, callback){
    callback = callback || function(){};
    userModel.findOne({openId: openId}, function(err, user){
        if(err) return callback(err)
        if(user){
            return callback(null, user);
        }else {
            API.getUser(openId, function(err2, newUser){
                if(err2) return callback(err2)
                user = new userModel({
                    openId: newUser.openid,
                    nickname: newUser.nickname,
                    sex: newUser.sex,
                    province: newUser.province,
                    city: newUser.city,
                    country: newUser.country,
                    headimgurl: newUser.headimgurl,
                    privilege: newUser.privilege,
                    createTime: new Date(),
                    lastUpdateTime: new Date()
                })
                user.save(function(err3){
                    if(err3) return callback(err3)
                    callback(null, user)
                })
            })
        }
    })
}

logger.js

const winston = require(winston);
const moment = require(moment);
const config = require(../conf/config);
let customLevels = {
    levels: {
        debug: 0,
        info: 1,
        warn: 2,
        error: 3
    },
    colors: {
        debug: blue,
        info: green,
        warn: yellow,
        error: red
    }
};

// create the main logger 等级高的包含等级低的输出日志
module.exports = logger = new (winston.Logger)({
    level: debug,
    levels: customLevels.levels,
    transports: [
        new (winston.transports.Console)({
            level: error,
            levels: customLevels.levels,
            timestamp: function(){return moment().format(YYYY-MM-DD HH:mm:ss)},
            colorize: true,
            silent: config.logStdout
        }),
        new (winston.transports.File)({
            name: info,
            filename: ./logs/info.log, //项目根目录
            maxsize: 1024 * 1024 * 50, //50M
            level: info,
            levels: customLevels.levels,
            timestamp: function(){return moment().format(YYYY-MM-DD HH:mm:ss)},
            json: false
        })
    ]
})
winston.addColors(customLevels.colors);

wechatApi.js

const config = require(../conf/config);
const mongoose = require(mongoose);
const Schema = require(mongoose).Schema;
const wechatApi = require(wechat-api);
const _ = require(underscore);

let Token = new Schema({
    accessToken: {type: String, required: true},
    expireTime: {type: Number, required: true},
    createTime: {type: Date, default: Date.now, required: true},
    expireAt: {type: Date, required: true, expires: 0, select: false}, //过期自动删除
    __v: {type: Number, select: false}
},{collection: token});
let tokenModel = mongoose.model(token, Token);

let BaseToken = {
    getWXToken: function(callback){
        tokenModel.findOne({},callback);
    },
    saveWXToken: function(token, callback){
        let update = _.clone(token);
        update.createTime = new Date();
        update.expireAt = new Date(update.expireTime);
        tokenModel.findOneAndUpdate({}, update, {upsert: true}, function(err){
            if(err) console.log(save token error : %s, err)
            callback(err)
        })
    }
}

module.exports.API = new wechatApi(config.wechat.appid, config.appSecret, BaseToken.getWXToken, BaseToken.saveWXToken);

 

wechat,wechat-api,mongoose,winston等的使用

标签:ons   token   middle   try   自动删除   ack   win   callback   mongodb   

原文地址:https://www.cnblogs.com/maoriaty/p/8410054.html


评论


亲,登录后才可以留言!