Initial code for Slack based search

This commit is contained in:
Jori Lallo
2016-08-22 23:37:01 -07:00
parent 70e46a5c05
commit 4f998bccc8
10 changed files with 131 additions and 37 deletions

View File

@@ -15,7 +15,7 @@ router.post('auth.slack', async (ctx) => {
const body = {
client_id: process.env.SLACK_KEY,
client_secret: process.env.SLACK_SECRET,
redirect_uri: process.env.SLACK_REDIRECT_URI,
redirect_uri: `${process.env.URL}/auth/slack/`,
code,
};
@@ -78,4 +78,29 @@ router.post('auth.slack', async (ctx) => {
} };
});
router.post('auth.slackCommands', async (ctx) => {
const { code } = ctx.body;
ctx.assertPresent(code, 'code is required');
const body = {
client_id: process.env.SLACK_KEY,
client_secret: process.env.SLACK_SECRET,
redirect_uri: `${process.env.URL}/auth/slack/commands`,
code,
};
let data;
try {
const response = await fetch(`https://slack.com/api/oauth.access?${querystring.stringify(body)}`);
data = await response.json();
} catch (e) {
throw httpErrors.BadRequest();
}
if (!data.ok) throw httpErrors.BadRequest(data.error);
ctx.body = { success: true };
});
export default router;

View File

@@ -78,25 +78,7 @@ router.post('documents.search', auth(), async (ctx) => {
const user = await ctx.state.user;
const sql = `
SELECT * FROM documents
WHERE "searchVector" @@ plainto_tsquery('english', :query) AND
"teamId" = '${user.teamId}'::uuid AND
"deletedAt" IS NULL
ORDER BY ts_rank(documents."searchVector", plainto_tsquery('english', :query))
DESC;
`;
const documents = await sequelize
.query(
sql,
{
replacements: {
query,
},
model: Document,
}
);
const documents = await Document.searchForUser(user, query);
const data = [];
await Promise.all(documents.map(async (document) => {

49
server/api/hooks.js Normal file
View File

@@ -0,0 +1,49 @@
import Router from 'koa-router';
import httpErrors from 'http-errors';
import { Document, User } from '../models';
const router = new Router();
router.post('hooks.slack', async (ctx) => {
const {
token,
user_id,
text,
} = ctx.body;
ctx.assertPresent(token, 'token is required');
ctx.assertPresent(user_id, 'user_id is required');
ctx.assertPresent(text, 'text is required');
if (token !== process.env.SLACK_VERIFICATION_TOKEN) throw httpErrors.BadRequest('Invalid token');
const user = await User.find({
where: {
slackId: user_id,
},
});
if (!user) throw httpErrors.BadRequest('Invalid user');
const documents = await Document.searchForUser(user, text, {
limit: 5,
});
const results = [];
let number = 1;
for (const document of documents) {
results.push(`${number}. <${process.env.URL}${document.getUrl()}|${document.title}>`);
number += 1;
}
ctx.body = {
text: 'Search results:',
attachments: [
{
text: results.join('\n'),
color: '#3AA3E3',
},
],
};
});
export default router;