博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
wechat,wechat-api,mongoose,winston等的使用
阅读量:5753 次
发布时间:2019-06-18

本文共 7607 字,大约阅读时间需要 25 分钟。

目录:

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);

 

转载于:https://www.cnblogs.com/maoriaty/p/8410054.html

你可能感兴趣的文章
linux命令经典用法与配置收录
查看>>
ensp-1.2.00.390练习STP实验。
查看>>
Python 入门指南python tutorial 2.7中文版
查看>>
华为 eNSP 配置 rip OSPF 路由重发布
查看>>
我的友情链接
查看>>
自建ngrok服务
查看>>
zabbix 监控 Vmware ESXI
查看>>
Windows 7 Service Pack 1 (SP1)远程桌面管理工具
查看>>
【转】init.d目录理解【转】
查看>>
win7 添加共享打印机登陆失败的问题!!!
查看>>
awk 用法详解!
查看>>
linux下添加路由的多种方法
查看>>
通过Jenkins API获得/检测Jenkins的Version
查看>>
关于Git的ssh公私钥非对称传输的一点理解
查看>>
用python编写daemon监控进程并自动恢复(附Shell版)
查看>>
u盘格式化的格式及分配单元大小
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
互联网创业公司最常见的失败原因
查看>>
学 Win32 汇编[9]: 子过程中的变量声明
查看>>