Skip to content

Commit

Permalink
added hot-load-demo
Browse files Browse the repository at this point in the history
  • Loading branch information
changong(龚澄) committed Mar 9, 2017
1 parent 1aad7d5 commit d8eab62
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 0 deletions.
92 changes: 92 additions & 0 deletions example/hot-reload-bot/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* Wechaty hot load dots demo
*
* DEV: docker run -ti -e --rm --volume="$(pwd)":/bot zixia/wechaty index.js
* PROD: docker run -ti -e NODE_ENV=production --rm --volume="$(pwd)":/bot zixia/wechaty index.js
*
* @author: Gcaufy
*
*/
const fs = require('fs');
const path = require('path');
const Wechaty = require('wechaty').default;

const isProd = process.env.NODE_ENV === 'production';
const bot = Wechaty.instance();

const EVENT_LIST = ['scan', 'logout', 'login', 'friend', 'room-join', 'room-leave', 'room-topic', 'message', 'heartbeat', 'error'];


// Load lisenter
const loadListener = (evt) => {
let fn;
try {
fn = require(`./listener/${evt}`);
console.log(`binded listener: ${evt}`);
} catch (e) {
fn = () => void 0;
if (e.toString().indexOf('Cannot find module') > -1) {
console.warn(`listener ${evt} is not defined.`);
} else {
console.error(e);
}
}
return fn;
}

// purge require cache
const purgeCache = (moduleName) => {
var mod = require.resolve(moduleName);
if (mod && ((mod = require.cache[mod]) !== undefined)) {
(function traverse(mod) {
mod.children.forEach(function (child) {
traverse(child);
});
delete require.cache[mod.id];
}(mod));
}

Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
if (cacheKey.indexOf(moduleName)>0) {
delete module.constructor._pathCache[cacheKey];
}
});
};

let eventHandler = {};


if (!isProd) { // start a watcher only if it's not production environment.
fs.watch('./listener', (e, filename) => {
let evt = filename.substring(0, filename.length - 3);
console.log(`${e}: ${filename}`);

if (EVENT_LIST.indexOf(evt) > -1) {
if (e === 'change') {
console.log(`${evt} listener reloaded.`);
purgeCache(`./listener/${evt}`);
// It may read an empty file, if not use setTimeout
setTimeout(() => {
bot.removeListener(evt, eventHandler[evt]);
//console.log('filecontent: ' + fs.readFileSync(`./listener/${evt}.js`));
eventHandler[evt] = loadListener(evt);
bot.on(evt, eventHandler[evt]);
}, 1000);
} else if (e === 'rename') {
console.log(`${evt} listener removed.`);
bot.removeListener(evt, eventHandler[evt]);
eventHandler[evt] = () => void 0;
bot.on(evt, eventHandler[evt]);
}
}
});
}

// Bind events
EVENT_LIST.forEach(evt => {
eventHandler[evt] = loadListener(evt);
bot.on(evt, eventHandler[evt]);
});


bot.init();
8 changes: 8 additions & 0 deletions example/hot-reload-bot/listener/friend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
exports = module.exports = async function onFriend (contact, request) {
if(request){
let name = contact.name();
await request.accept();

console.log(`Contact: ${name} send request ${request.hello}`);
}
}
3 changes: 3 additions & 0 deletions example/hot-reload-bot/listener/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
exports = module.exports = function onLoging (user) {
console.log(`${user} login`);
}
22 changes: 22 additions & 0 deletions example/hot-reload-bot/listener/message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
exports = module.exports = async function onMessage (message) {
const room = message.room();
const sender = message.from();
const content = message.content();

const topic = room ? '[' + room.topic() + ']' : '';


console.log(`${topic} <${sender.name()}> : ${message.toStringDigest()}`);

if (message.self() || room) {
console.log('message is sent from myself, or inside a room.');
return;
}

if (content === 'ding') {
message.say('thanks for ding me...');
} else {
sender.say('auto reply.');
return;
}
}
5 changes: 5 additions & 0 deletions example/hot-reload-bot/listener/scan.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
exports = module.exports = function onScan (url, code) {
let loginUrl = url.replace('qrcode', 'l');
require('qrcode-terminal').generate(loginUrl);
console.log(url);
}

0 comments on commit d8eab62

Please sign in to comment.