From 3f9d0c0fe1225c7c9693eccfba393ebb7889f253 Mon Sep 17 00:00:00 2001 From: Iswan Jumat Date: Sat, 1 Oct 2016 18:31:54 +0530 Subject: [PATCH 1/3] fixed lint issues --- .eslintrc | 5 +++ app.js | 34 +++++++-------- messenger.js | 90 +++++++++++++++++++-------------------- package.json | 7 +-- scripts/i18n-generator.js | 10 ++--- youpin-api.js | 59 +++++++++++-------------- youpin.js | 1 + 7 files changed, 98 insertions(+), 108 deletions(-) diff --git a/.eslintrc b/.eslintrc index a789d7c..59e3512 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,5 +5,10 @@ "browser": true, "es6": true }, + rules: { + "no-underscore-dangle": 0, + "no-console": 0, + "global-require": 0, + }, "plugins": [] } diff --git a/app.js b/app.js index 725049f..4e9a31c 100644 --- a/app.js +++ b/app.js @@ -1,5 +1,3 @@ -'use strict'; - const bodyParser = require('body-parser'); const config = require('config'); const express = require('express'); @@ -29,9 +27,11 @@ const API_PASSWORD = (process.env.API_PASSWORD) ? const API_USER_ID = (process.env.API_USER_ID) ? process.env.API_USER_ID : config.get('apiUserId'); -if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN && API_URI && API_USERNAME && API_PASSWORD && API_USER_ID)) { - console.error('Missing config values'); - process.exit(1); +if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN)) { + if (API_URI && API_USERNAME && API_PASSWORD && API_USER_ID) { + console.error('Missing config values'); + process.exit(1); + } } @@ -53,21 +53,22 @@ const m = require('./messenger.js')(PAGE_ACCESS_TOKEN); const conversation = require('./conversation.js')(config.get('sessionMaxLength')); // Youpin API utils -const api_lib = require('./youpin-api.js'); -var youpin; -new api_lib(API_URI, API_USERNAME, API_PASSWORD).then(function(api) { +const ApiLib = require('./youpin-api.js'); + +let youpin; +new ApiLib(API_URI, API_USERNAME, API_PASSWORD).then((api) => { // Youpin bot youpin = require('./youpin.js')(m, api, conversation, API_USER_ID); }); // Index route -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('ทดลองคุยกับป้ายุพินได้ที่ https://m.me/youpin.city.test'); }); // Webhook verification -app.get('/webhook/', function (req, res) { +app.get('/webhook/', (req, res) => { if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === config.get('validationToken')) { res.status(200).send(req.query['hub.challenge']); @@ -77,7 +78,7 @@ app.get('/webhook/', function (req, res) { // Handle messages -app.post('/webhook/', function(req, res) { +app.post('/webhook/', (req, res) => { // Verify signature if (req.isXHub) { if (req.isXHubValid()) { @@ -89,15 +90,14 @@ app.post('/webhook/', function(req, res) { return; } - let data = req.body; - if (data.object == 'page') { - data.entry.forEach((pageEntry) => { + const data = req.body; + if (data.object === 'page') { + data.entry.forEach((pageEntry) => { pageEntry.messaging.forEach((msgEvent) => { if (msgEvent.message || msgEvent.postback) { youpin.onMessaged(msgEvent); } else { - console.log('Webhook received unhandled messaging event: ' + - msgEvent); + console.log(`Webhook received unhandled messaging event: ${msgEvent}`); } }); }); @@ -105,6 +105,6 @@ app.post('/webhook/', function(req, res) { }); -app.listen(app.get('port'), function() { +app.listen(app.get('port'), () => { console.log(`Node app is running on port ${app.get('port')}`); }); diff --git a/messenger.js b/messenger.js index 36bdc5d..a329a97 100644 --- a/messenger.js +++ b/messenger.js @@ -1,7 +1,6 @@ const request = require('request'); module.exports = (PAGE_ACCESS_TOKEN) => { - function _callSendAPI(messageData) { request( { @@ -9,10 +8,10 @@ module.exports = (PAGE_ACCESS_TOKEN) => { qs: { access_token: PAGE_ACCESS_TOKEN }, method: 'POST', json: messageData, - headers: {'Content-Type': 'application/json'}, + headers: { 'Content-Type': 'application/json' }, }, - function (error, response, body) { - if (!error && response.statusCode == 200) { + (error, response, body) => { + if (!error && response.statusCode === 200) { console.log('Successfully sent generic message ' + `with id ${body.message_id} to recipient ${body.recipient_id}`); } else { @@ -25,101 +24,101 @@ module.exports = (PAGE_ACCESS_TOKEN) => { } return { - sendImage: function(userid, url) { + sendImage(userid, url) { const messageData = { recipient: { - id: userid + id: userid, }, message: { attachment: { type: 'image', payload: { - url: url - } - } - } + url, + }, + }, + }, }; _callSendAPI(messageData); }, - sendText: function(userid, text) { + sendText(userid, text) { const messageData = { recipient: { - id: userid + id: userid, }, message: { - text: text - } + text, + }, }; _callSendAPI(messageData); }, - sendTextWithReplies: function(userid, text, replies) { + sendTextWithReplies(userid, text, replies) { const messageData = { recipient: { - id: userid + id: userid, }, message: { - text: text, - quick_replies: replies - } + text, + quick_replies: replies, + }, }; _callSendAPI(messageData); }, - sendButton: function(userid, text, buttons) { + sendButton(userid, text, buttons) { const messageData = { recipient: { - id: userid + id: userid, }, message: { attachment: { type: 'template', payload: { template_type: 'button', - text: text, - buttons: buttons - } - } - } + text, + buttons, + }, + }, + }, }; _callSendAPI(messageData); }, - sendGeneric: function(userid, elements) { + sendGeneric(userid, elements) { const messageData = { recipient: { - id: userid + id: userid, }, message: { attachment: { type: 'template', payload: { template_type: 'generic', - elements: elements - } - } - } + elements, + }, + }, + }, }; _callSendAPI(messageData); }, - getProfile: function(userid, callback) { + getProfile(userid, callback) { request( { - uri: 'https://graph.facebook.com/v2.6/' + userid, + uri: `https://graph.facebook.com/v2.6/${userid}`, qs: { fields: 'first_name,last_name,profile_pic,locale,timezone,gender', - access_token: PAGE_ACCESS_TOKEN + access_token: PAGE_ACCESS_TOKEN, }, method: 'GET', - json: true + json: true, }, - function (error, response, body) { - if (!error && response.statusCode == 200) { + (error, response, body) => { + if (!error && response.statusCode === 200) { callback(body); } else { console.error('Unable to get user profile.'); @@ -130,21 +129,20 @@ module.exports = (PAGE_ACCESS_TOKEN) => { ); }, - createPostbackButton: function(title, payload) { + createPostbackButton(title, payload) { return { type: 'postback', - title: title, - payload: payload + title, + payload, }; }, - createQuickReplyButton: function(title, payload) { + createQuickReplyButton(title, payload) { return { content_type: 'text', - title: title, - payload: payload + title, + payload, }; - } + }, }; - }; diff --git a/package.json b/package.json index 215798b..aa7d353 100644 --- a/package.json +++ b/package.json @@ -13,11 +13,9 @@ "dependencies": { "asyncawait": "^1.0.6", "bluebird": "^3.4.3", + "string-saw": "0.0.25", "body-parser": "^1.15.2", "config": "^1.21.0", - "eslint-plugin-import": "^1.9.2", - "eslint-plugin-jsx-a11y": "^1.5.3", - "eslint-plugin-react": "^5.2.2", "express": "^4.14.0", "express-x-hub": "^1.0.4", "feathers": "^2.0.1", @@ -38,7 +36,6 @@ "eslint-plugin-import": "^1.9.2", "eslint-plugin-jsx-a11y": "^1.5.3", "eslint-plugin-react": "^5.2.2", - "lodash": "^4.15.0", - "string-saw": "0.0.25" + "lodash": "^4.15.0" } } diff --git a/scripts/i18n-generator.js b/scripts/i18n-generator.js index abb6ae5..625684a 100644 --- a/scripts/i18n-generator.js +++ b/scripts/i18n-generator.js @@ -10,7 +10,7 @@ const files = ['youpin.js']; function extractKeysFromFile(file) { return fs.readFileAsync(file, 'utf8') - .then(data => { + .then((data) => { const keys = saw(data) .split(os.EOL) .map(line => saw(line) @@ -26,7 +26,7 @@ function extractKeysFromFile(file) { function updateKeysToFile(keys, lang) { const file = `${i18nConfig.directory}/${lang}.json`; fs.readFileAsync(file, 'utf8') - .then(data => { + .then((data) => { console.log(`Updating ${file}`); const oldKeys = JSON.parse(data); const mergedKeys = _.merge(keys, oldKeys); @@ -38,19 +38,19 @@ function updateKeysToFile(keys, lang) { }); } -Promise.map(files, extractKeysFromFile).then(items => { +Promise.map(files, extractKeysFromFile).then((items) => { const keys = _.chain(items) .flatten() .uniq() .sort() .transform((obj, a) => { - obj[a] = ''; + obj[a] = ''; // eslint-disable-line }, {}) .value(); console.log(`We have ${_.keys(keys).length} i18n keys.`); - _.each(i18nConfig.locales, lang => { + _.each(i18nConfig.locales, (lang) => { updateKeysToFile(keys, lang); }); }); diff --git a/youpin-api.js b/youpin-api.js index c1cfadf..b2c414b 100644 --- a/youpin-api.js +++ b/youpin-api.js @@ -1,7 +1,4 @@ -'use strict'; - const request = require('superagent'); - const feathers = require('feathers/client'); const rest = require('feathers-rest/client'); const hooks = require('feathers-hooks'); @@ -11,7 +8,7 @@ class Api { // initialise api and do authentication constructor(uri, username, password) { this.uri = uri; - this.token; + this.token = null; this.username = username; this.password = password; const app = feathers() @@ -20,21 +17,17 @@ class Api { .configure(authentication()); setInterval(() => { - api.refreshToken(); + Api.refreshToken(); }, 23 * 60 * 60000); // Refresh token every 23 hours - return new Promise((resolve, reject) => { - app.authenticate({ - type: 'local', - 'email': username, - 'password': password - }).then(result => { - this.token = app.get('token'); - resolve(this); - }).catch(error => { - console.log(error); - reject(error); - }); + app.authenticate({ + type: 'local', + email: this.username, + password: this.password, + }).then(() => { + this.token = app.get('token'); + }).catch((error) => { + console.log(error); }); } @@ -45,27 +38,23 @@ class Api { .configure(rest(this.uri).superagent(request)) .configure(authentication()); - new Promise((resolve, reject) => { - app.authenticate({ - type: 'local', - 'email': this.username, - 'password': this.password - }).then(result => { - this.token = app.get('token'); - resolve(this); - }).catch(error => { - console.log(error); - reject(error); - }); + app.authenticate({ + type: 'local', + email: this.username, + password: this.password, + }).then(() => { + this.token = app.get('token'); + }).catch((error) => { + console.log(error); }); } postPin(json, callback) { request - .post(this.uri + '/pins') - .set('Authorization', 'Bearer ' + this.token) + .post(`${this.uri}/pins`) + .set('Authorization', `Bearer ${this.token}`) .send(json) - .end(function (error, response) { + .end((error, response) => { if (!error && response.ok) { callback(response.body); } else { @@ -78,9 +67,9 @@ class Api { uploadPhotoFromURL(imgLink, callback) { request - .post(this.uri + '/photos/upload_from_url') + .post(`${this.uri}/photos/upload_from_url`) .send({ url: imgLink }) - .end(function (error, response) { + .end((error, response) => { if (!error && response.ok) { callback(response.body); } else { @@ -90,6 +79,6 @@ class Api { } }); } -}; +} module.exports = Api; diff --git a/youpin.js b/youpin.js index 2ace3aa..dc7249d 100644 --- a/youpin.js +++ b/youpin.js @@ -152,6 +152,7 @@ module.exports = (m, api, conversation, apiUserId) => { console.log(event.postback); const postback = event.postback ? event.postback.payload : undefined; + // eslint-disable-next-line let context = await (conversation.getContext(userid)); console.log("---- Loaded previous context" ) ; From 6e76a4e6bf7e95eff1c391e0da243b430fe72104 Mon Sep 17 00:00:00 2001 From: Iswan Jumat Date: Sun, 2 Oct 2016 23:40:02 +0530 Subject: [PATCH 2/3] Fixed split if logic to two line --- app.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/app.js b/app.js index 4e9a31c..efd4161 100644 --- a/app.js +++ b/app.js @@ -27,11 +27,10 @@ const API_PASSWORD = (process.env.API_PASSWORD) ? const API_USER_ID = (process.env.API_USER_ID) ? process.env.API_USER_ID : config.get('apiUserId'); -if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN)) { - if (API_URI && API_USERNAME && API_PASSWORD && API_USER_ID) { - console.error('Missing config values'); - process.exit(1); - } +// eslint-disable-next-line max-len +if (!(APP_SECRET && VALIDATION_TOKEN && PAGE_ACCESS_TOKEN && API_URI && API_USERNAME && API_PASSWORD && API_USER_ID)) { + console.error('Missing config values'); + process.exit(1); } From aaf40cdb402402e74bacf803e452b76d298d556b Mon Sep 17 00:00:00 2001 From: Iswan Jumat Date: Mon, 3 Oct 2016 11:10:20 +0530 Subject: [PATCH 3/3] fixed return promise inside contructor --- youpin-api.js | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/youpin-api.js b/youpin-api.js index b2c414b..2eefe5c 100644 --- a/youpin-api.js +++ b/youpin-api.js @@ -20,14 +20,18 @@ class Api { Api.refreshToken(); }, 23 * 60 * 60000); // Refresh token every 23 hours - app.authenticate({ - type: 'local', - email: this.username, - password: this.password, - }).then(() => { - this.token = app.get('token'); - }).catch((error) => { - console.log(error); + return new Promise((resolve, reject) => { + app.authenticate({ + type: 'local', + email: username, + password: password, //eslint-disable-line object-shorthand + }).then(() => { + this.token = app.get('token'); + resolve(this); + }).catch(error => { + console.log(error); + reject(error); + }); }); }