Teams API

node v8.12.0
version: 2.0.0
endpointsharetweet
const express = require('@runkit/runkit/express-endpoint/1.0.0'); const AWS = require('aws-sdk'); const request = require('request'); const rp = require('request-promise'); AWS.config.update({ region: 'us-east-1', accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY }); const teamTableName = process.env.AWS_TEAM_TABLE; const getClient = () => { return new AWS.DynamoDB.DocumentClient(); }; const getAllTeams = () => { return getClient() .scan({ TableName: teamTableName }) .promise(); }; const getTeamById = id => { return getClient() .get({ TableName: teamTableName, Key: { 'team-id': id } }) .promise(); }; const getTeamByName = name => { return getClient() .query({ TableName: teamTableName, IndexName: 'team-name-index', KeyConditionExpression: '#name = :hkey', ExpressionAttributeNames: { '#name': 'team-name' }, ExpressionAttributeValues: { ':hkey': name, } }) .promise(); }; const mapTeam = record => { return { id: record['team-id'], name: record['team-name'], members: record.members.map(member => { return { personId: member['people-id'] }; }) }; }; const mapTeamMembers = (teamMembers, people) => { return people.map(person => { const member = teamMembers.find(member => member.personId === person.id); return Object.assign({}, member, { firstName: person.firstName, lastName: person.lastName, email: person.email, shortname: person.shortname }); }); }; const buildPersonRequest = id => { return rp({ uri: `https://untitled-19481xph5q2f.runkit.sh/people/${id}`, json: true }); }; const app = express(exports); app.set('json spaces', 2); app.get('/teams', (req, res, next) => { if (req.query.name) { return getTeamByName(req.query.name) .then(result => { res.json(result.Items.map(mapTeam)); }) .catch(next); } return getAllTeams() .then(result => { const teams = result.Items.map(mapTeam) if (req.query.person_id) { const teamsWithPerson = teams.filter((team => { return team.members.find(member => member.personId === req.query.person_id) })) return res.json(teamsWithPerson) } return res.json(teams); }) .catch(next); }); app.get('/teams/:id', (req, res, next) => { return getTeamById(req.params.id) .then(result => { if (!result.Item) { return res.status(404).json({ message: 'team not found.' }); } const team = mapTeam(result.Item); return Promise.all( team.members.map(member => buildPersonRequest(member.personId)) ).then(people => { return res.json({ id: team.id, name: team.name, members: mapTeamMembers(team.members, people) }); }); }) .catch(next); }); app.get('/', (req, res) => res.json({ message: 'Teams API' }));
Loading…

no comments

    sign in to comment