2017-09-04 00:08:56 +00:00
|
|
|
// @flow
|
|
|
|
import fetch from 'isomorphic-fetch';
|
|
|
|
import querystring from 'querystring';
|
2018-02-20 07:31:18 +00:00
|
|
|
import httpErrors from 'http-errors';
|
2017-09-04 00:08:56 +00:00
|
|
|
|
|
|
|
const SLACK_API_URL = 'https://slack.com/api';
|
|
|
|
|
2017-12-19 03:59:29 +00:00
|
|
|
export async function post(endpoint: string, body: Object) {
|
|
|
|
let data;
|
|
|
|
try {
|
|
|
|
const token = body.token;
|
|
|
|
const response = await fetch(`${SLACK_API_URL}/${endpoint}`, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bearer ${token}`,
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
});
|
|
|
|
data = await response.json();
|
|
|
|
} catch (e) {
|
|
|
|
throw httpErrors.BadRequest();
|
|
|
|
}
|
|
|
|
if (!data.ok) throw httpErrors.BadRequest(data.error);
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
2017-09-04 00:08:56 +00:00
|
|
|
export async function request(endpoint: string, body: Object) {
|
|
|
|
let data;
|
|
|
|
try {
|
|
|
|
const response = await fetch(
|
|
|
|
`${SLACK_API_URL}/${endpoint}?${querystring.stringify(body)}`
|
|
|
|
);
|
|
|
|
data = await response.json();
|
|
|
|
} catch (e) {
|
|
|
|
throw httpErrors.BadRequest();
|
|
|
|
}
|
|
|
|
if (!data.ok) throw httpErrors.BadRequest(data.error);
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function oauthAccess(
|
|
|
|
code: string,
|
|
|
|
redirect_uri: string = `${process.env.URL || ''}/auth/slack`
|
|
|
|
) {
|
|
|
|
return request('oauth.access', {
|
|
|
|
client_id: process.env.SLACK_KEY,
|
|
|
|
client_secret: process.env.SLACK_SECRET,
|
2017-10-20 04:02:39 +00:00
|
|
|
redirect_uri,
|
2017-09-04 00:08:56 +00:00
|
|
|
code,
|
|
|
|
});
|
|
|
|
}
|