Published 8/19/2017
Mini Project: Npm search in slack

Npm search in slack (mini project)

This simple hacky project can be used to learn Slack to search npm repository. Search npm and share results with other developers in you team.

See how it works!

Usage

Just run on Slack:

/wt npm PACKAGE_KEYWORD

Example

Environment

We need Slack and Webtask.io to make magic work.

Webtask Slack Intro:

Magic

You need to allow Webtask access to your Slack. Just follow Webtask's Slack tutorial and you are prepared to have fun.

Code

Code needs to be placed inside webhook created by /wt make SCRIPT_NAME in Slack. Code will be running on webtask.io on each run of command /wt SCRIPT_NAME PARAMS, in this case it's specifically /wt npm PACKAGE

Just single dependency is required:

"node-fetch": "^1.7.2"

Here is full code using official npmjs search API:

const nodeFetch = require('node-fetch');

const shortenString = (text, max) => (text.length <= max ? text : text.substring(0, max) + '...');

const SHOW_COUNT = 8;

const searchNpm = keyword => nodeFetch(`https://api.npms.io/v2/search?q=${keyword}`).then(res => res.json());

module.exports = (ctx, cb) => {
  const keyword = ctx.body.text;
  const repos = searchNpm(keyword).then(json => {
    const repos = json.results
      .slice(0, SHOW_COUNT)
      .map(item => {
        const packg = item.package;
        const description = shortenString(packg.description.toString(), 30);
        const date = new Date(packg.date).toLocaleDateString();
        const link = packg.links.homepage || packg.links.repository || packg.links.npm;
        const author = packg.publisher.username;
        const authorLink = `https://www.npmjs.com/~${author}`;
        return `\`<${link}|${packg.name}>:${packg.version}\` by *<${authorLink}|${author}>* ${description} _(Updated \`${date})\`_`;
      })
      .join('\n');
    const notShownCount = json.total - Math.min(json.results.length, SHOW_COUNT);
    cb(null, {
      response_type: 'in_channel',
      text:
        `@${ctx.body.user_name} searched on npm with keyword '${keyword}':\n ${repos}` +
        (notShownCount > 0 ? `\nAnd ${notShownCount} more...` : '')
    });
  });
};

Thanks Auth0 and Webtask for providing interesting "instant deploy" environment.