diff --git a/datastore/concepts.js b/datastore/concepts.js index 790f01fd66..f7611d9c42 100644 --- a/datastore/concepts.js +++ b/datastore/concepts.js @@ -165,33 +165,33 @@ Entity.prototype.testEntityWithParent = function (callback) { Entity.prototype.testProperties = function (callback) { // jshint camelcase:false // [START properties] - var task = [ - { - name: 'type', - value: 'Personal' - }, - { - name: 'created', - value: new Date() - }, - { - name: 'done', - value: false - }, - { - name: 'priority', - value: 4 - }, - { - name: 'percent_complete', - value: 10.0 - }, - { - name: 'description', - value: 'Learn Cloud Datastore', - excludeFromIndexes: true - } - ]; + var task = [ + { + name: 'type', + value: 'Personal' + }, + { + name: 'created', + value: new Date() + }, + { + name: 'done', + value: false + }, + { + name: 'priority', + value: 4 + }, + { + name: 'percent_complete', + value: 10.0 + }, + { + name: 'description', + value: 'Learn Cloud Datastore', + excludeFromIndexes: true + } + ]; // [END properties] this.datastore.save({ diff --git a/datastore/tasks.js b/datastore/tasks.js index c8334abbe4..1124e7f2b3 100755 --- a/datastore/tasks.js +++ b/datastore/tasks.js @@ -72,7 +72,7 @@ function addTask (description, callback) { datastore.save({ key: taskKey, - data: [ + data: [ { name: 'created', value: new Date().toJSON() diff --git a/functions/README.md b/functions/README.md index 97d5b1cf16..3739f6c6b4 100644 --- a/functions/README.md +++ b/functions/README.md @@ -32,3 +32,4 @@ environment. * [Modules](module/) * [OCR (Optical Character Recognition)](ocr/) * [SendGrid](sendgrid/) +* [Slack](slack/) diff --git a/functions/slack/.gitignore b/functions/slack/.gitignore new file mode 100644 index 0000000000..254077b7f3 --- /dev/null +++ b/functions/slack/.gitignore @@ -0,0 +1,4 @@ +node_modules +config.json +test.js +test/ \ No newline at end of file diff --git a/functions/slack/README.md b/functions/slack/README.md new file mode 100644 index 0000000000..df4664ea8d --- /dev/null +++ b/functions/slack/README.md @@ -0,0 +1,14 @@ +Google Cloud Platform logo + +# Google Cloud Functions Slack Slash Command sample + +This tutorial demonstrates using Cloud Functions to implement a Slack Slash +Command that searches the Google Knowledge Graph API. + +View the [source code][code]. + +[code]: index.js + +## Deploy and Test + +Read the tutorial at https://cloud.google.com/functions/docs/tutorials/slack diff --git a/functions/slack/config.default.json b/functions/slack/config.default.json new file mode 100644 index 0000000000..349305e826 --- /dev/null +++ b/functions/slack/config.default.json @@ -0,0 +1,4 @@ +{ + "SLACK_TOKEN": "[YOUR_SLACK_TOKEN]", + "KG_API_KEY": "[YOUR_KG_API_KEY]" +} \ No newline at end of file diff --git a/functions/slack/index.js b/functions/slack/index.js new file mode 100644 index 0000000000..e07217dd75 --- /dev/null +++ b/functions/slack/index.js @@ -0,0 +1,162 @@ +// Copyright 2016, Google, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +// [START setup] +var config = require('./config.json'); +var googleapis = require('googleapis'); + +// Get a reference to the Knowledge Graph Search component +var kgsearch = googleapis.kgsearch('v1'); +// [END setup] + +// [START formatSlackMessage] +/** + * Format the Knowledge Graph API response into a richly formatted Slack message. + * + * @param {string} query The user's search query. + * @param {Object} response The response from the Knowledge Graph API. + * @returns {Object} The formatted message. + */ +function formatSlackMessage (query, response) { + var entity; + + // Extract the first entity from the result list, if any + if (response && response.itemListElement && + response.itemListElement.length) { + entity = response.itemListElement[0].result; + } + + // Prepare a rich Slack message + // See https://api.slack.com/docs/message-formatting + var slackMessage = { + response_type: 'in_channel', + text: 'Query: ' + query, + attachments: [] + }; + + if (entity) { + var attachment = { + color: '#3367d6' + }; + if (entity.name) { + attachment.title = entity.name; + if (entity.description) { + attachment.title = attachment.title + ': ' + entity.description; + } + } + if (entity.detailedDescription) { + if (entity.detailedDescription.url) { + attachment.title_link = entity.detailedDescription.url; + } + if (entity.detailedDescription.articleBody) { + attachment.text = entity.detailedDescription.articleBody; + } + } + if (entity.image && entity.image.contentUrl) { + attachment.image_url = entity.image.contentUrl; + } + slackMessage.attachments.push(attachment); + } else { + slackMessage.attachments.push({ + text: 'No results match your query...' + }); + } + + return slackMessage; +} +// [END formatSlackMessage] + +// [START verifyWebhook] +/** + * Verify that the webhook request came from Slack. + * + * @param {Object} body The body of the request. + * @param {string} body.token The Slack token to be verified. + */ +function verifyWebhook (body) { + if (!body || body.token !== config.SLACK_TOKEN) { + var error = new Error('Invalid credentials'); + error.code = 401; + throw error; + } +} +// [END verifyWebhook] + +// [START makeSearchRequest] +/** + * Send the user's search query to the Knowledge Graph API. + * + * @param {string} query The user's search query. + * @param {Function} callback Callback function. + */ +function makeSearchRequest (query, callback) { + kgsearch.entities.search({ + auth: config.KG_API_KEY, + query: query, + limit: 1 + }, function (err, response) { + if (err) { + return callback(err); + } + + // Return a formatted message + return callback(null, formatSlackMessage(query, response)); + }); +} +// [END makeSearchRequest] + +// [START kgSearch] +/** + * Receive a Slash Command request from Slack. + * + * Trigger this function by making a POST request with a payload to: + * https://[YOUR_REGION].[YOUR_PROJECT_ID].cloudfunctions.net/kgsearch + * + * @example + * curl -X POST "https://us-central1.your-project-id.cloudfunctions.net/kgSearch" --data '{"token":"[YOUR_SLACK_TOKEN]","text":"giraffe"}' + * + * @param {Object} req Cloud Function request object. + * @param {Object} req.body The request payload. + * @param {string} req.body.token Slack's verification token. + * @param {string} req.body.text The user's search query. + * @param {Object} res Cloud Function response object. + */ +exports.kgSearch = function kgSearch (req, res) { + try { + if (req.method !== 'POST') { + var error = new Error('Only POST requests are accepted'); + error.code = 405; + throw error; + } + + // Verify that this request came from Slack + verifyWebhook(req.body); + + // Make the request to the Knowledge Graph Search API + makeSearchRequest(req.body.text, function (err, response) { + if (err) { + console.error(err); + return res.status(500); + } + + // Send the formatted message back to Slack + return res.json(response); + }); + } catch (err) { + console.error(err); + return res.status(err.code || 500).send(err.message); + } +}; +// [END kgSearch] diff --git a/functions/slack/package.json b/functions/slack/package.json new file mode 100644 index 0000000000..b327543785 --- /dev/null +++ b/functions/slack/package.json @@ -0,0 +1,15 @@ +{ + "name": "nodejs-docs-samples-functions-slack", + "description": "Node.js samples found on https://cloud.google.com", + "version": "0.0.1", + "private": true, + "license": "Apache Version 2.0", + "author": "Google Inc.", + "repository": { + "type": "git", + "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git" + }, + "dependencies": { + "googleapis": "^11.0.0" + } +} diff --git a/test/functions/slack.test.js b/test/functions/slack.test.js new file mode 100644 index 0000000000..2d2ead804b --- /dev/null +++ b/test/functions/slack.test.js @@ -0,0 +1,228 @@ +// Copyright 2016, Google, Inc. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +var proxyquire = require('proxyquire').noCallThru(); + +var method = 'POST'; +var query = 'giraffe'; +var SLACK_TOKEN = 'slack-token'; +var KG_API_KEY = 'kg-api-key'; + +function getSample () { + var config = { + SLACK_TOKEN: SLACK_TOKEN, + KG_API_KEY: KG_API_KEY + }; + var kgsearch = { + entities: { + search: sinon.stub().callsArg(1) + } + }; + var googleapis = { + kgsearch: sinon.stub().returns(kgsearch) + }; + return { + sample: proxyquire('../../functions/slack', { + googleapis: googleapis, + './config.json': config + }), + mocks: { + googleapis: googleapis, + kgsearch: kgsearch, + config: config + } + }; +} + +function getMocks () { + var req = { + headers: {}, + query: {}, + body: {}, + get: function (header) { + return this.headers[header]; + } + }; + sinon.spy(req, 'get'); + var res = { + headers: {}, + send: sinon.stub().returnsThis(), + json: sinon.stub().returnsThis(), + end: sinon.stub().returnsThis(), + status: function (statusCode) { + this.statusCode = statusCode; + return this; + }, + set: function (header, value) { + this.headers[header] = value; + return this; + } + }; + sinon.spy(res, 'status'); + sinon.spy(res, 'set'); + return { + req: req, + res: res + }; +} + +describe('functions:slack', function () { + it('Send fails if not a POST request', function () { + var expectedMsg = 'Only POST requests are accepted'; + var mocks = getMocks(); + + getSample().sample.kgSearch(mocks.req, mocks.res); + + assert.equal(mocks.res.status.calledOnce, true); + assert.equal(mocks.res.status.firstCall.args[0], 405); + assert.equal(mocks.res.send.calledOnce, true); + assert.equal(mocks.res.send.firstCall.args[0], expectedMsg); + assert(console.error.called); + }); + + it('Throws if invalid slack token', function () { + var expectedMsg = 'Invalid credentials'; + var mocks = getMocks(); + + mocks.req.method = method; + mocks.req.body.token = 'wrong'; + var slackSample = getSample(); + slackSample.sample.kgSearch(mocks.req, mocks.res); + + assert.equal(mocks.res.status.calledOnce, true); + assert.equal(mocks.res.status.firstCall.args[0], 401); + assert.equal(mocks.res.send.calledOnce, true); + assert.equal(mocks.res.send.firstCall.args[0], expectedMsg); + assert(console.error.called); + }); + + it('Handles search error', function () { + var mocks = getMocks(); + + mocks.req.method = method; + mocks.req.body.token = SLACK_TOKEN; + mocks.req.body.text = query; + var slackSample = getSample(); + slackSample.mocks.kgsearch.entities.search = sinon.stub().callsArgWith(1, 'error'); + slackSample.sample.kgSearch(mocks.req, mocks.res); + + assert.equal(mocks.res.status.calledOnce, true); + assert.equal(mocks.res.status.firstCall.args[0], 500); + assert.equal(mocks.res.send.called, false); + assert(console.error.calledWith('error')); + }); + + it('Makes search request, receives empty results', function () { + var mocks = getMocks(); + + mocks.req.method = method; + mocks.req.body.token = SLACK_TOKEN; + mocks.req.body.text = query; + var slackSample = getSample(); + slackSample.mocks.kgsearch.entities.search = sinon.stub().callsArgWith(1, null, { + itemListElement: [] + }); + slackSample.sample.kgSearch(mocks.req, mocks.res); + + assert.equal(mocks.res.status.called, false); + assert.equal(mocks.res.json.called, true); + assert.deepEqual(mocks.res.json.firstCall.args[0], { + text: 'Query: ' + query, + response_type: 'in_channel', + attachments: [ + { + text: 'No results match your query...' + } + ] + }); + }); + + it('Makes search request, receives non-empty results', function () { + var mocks = getMocks(); + + mocks.req.method = method; + mocks.req.body.token = SLACK_TOKEN; + mocks.req.body.text = query; + var slackSample = getSample(); + slackSample.mocks.kgsearch.entities.search = sinon.stub().callsArgWith(1, null, { + itemListElement: [ + { + result: { + name: 'Giraffe', + description: 'Animal', + detailedDescription: { + url: 'http://domain.com/giraffe', + articleBody: 'giraffe is a tall animal' + }, + image: { + contentUrl: 'http://domain.com/image.jpg' + } + } + } + ] + }); + slackSample.sample.kgSearch(mocks.req, mocks.res); + + assert.equal(mocks.res.status.called, false); + assert.equal(mocks.res.json.called, true); + assert.deepEqual(mocks.res.json.firstCall.args[0], { + text: 'Query: ' + query, + response_type: 'in_channel', + attachments: [ + { + color: '#3367d6', + title: 'Giraffe: Animal', + title_link: 'http://domain.com/giraffe', + text: 'giraffe is a tall animal', + image_url: 'http://domain.com/image.jpg' + } + ] + }); + }); + + it('Makes search request, receives non-empty results but partial data', function () { + var mocks = getMocks(); + + mocks.req.method = method; + mocks.req.body.token = SLACK_TOKEN; + mocks.req.body.text = query; + var slackSample = getSample(); + slackSample.mocks.kgsearch.entities.search = sinon.stub().callsArgWith(1, null, { + itemListElement: [ + { + result: { + name: 'Giraffe', + detailedDescription: {}, + image: {} + } + } + ] + }); + slackSample.sample.kgSearch(mocks.req, mocks.res); + + assert.equal(mocks.res.status.called, false); + assert.equal(mocks.res.json.called, true); + assert.deepEqual(mocks.res.json.firstCall.args[0], { + text: 'Query: ' + query, + response_type: 'in_channel', + attachments: [ + { + color: '#3367d6', + title: 'Giraffe' + } + ] + }); + }); +});