Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add api endpoints #281

Merged
merged 4 commits into from
Oct 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion babel.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
require('babel-register')
require('babel-polyfill')
require('./app/index')
require('./server/app/index')
3 changes: 1 addition & 2 deletions helpers/calculate.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import Handlebars from 'handlebars'
import _ from 'lodash'

import { timeDiff } from '../lib/parse/time'

export const isNewPromise = ({ promise }) => promise.clix === 1
import { isNewPromise } from '../server/models/promise'

Handlebars.registerHelper('dueStatus', (dueDate) => {
if (!dueDate) return ''
Expand Down
5 changes: 5 additions & 0 deletions helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import './calculate'
import './colors'
import './format'
import './path'
import './utils'
2 changes: 1 addition & 1 deletion helpers/path.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Handlebars from 'handlebars'
import APP_DOMAIN from '../app/config'
import APP_DOMAIN from '../server/app/config'

const userPath = (name) => `//${name}.${APP_DOMAIN}`
export const promisePath = ({ username, urtext }) =>
Expand Down
2 changes: 1 addition & 1 deletion helpers/utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Handlebars from 'handlebars'
import moment from 'moment-timezone'

import APP_DOMAIN from '../app/config'
import APP_DOMAIN from '../server/app/config'
import { promisePath } from './path'

Handlebars.registerHelper('__appDomain', () => {
Expand Down
2 changes: 1 addition & 1 deletion lib/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
PAPERTRAIL_HOST,
PAPERTRAIL_PORT,
PAPERTRAIL_LEVEL
} from '../app/config'
} from '../server/app/config'

const { formatter, timestamp } = consoleFormatter()

Expand Down
2 changes: 1 addition & 1 deletion lib/mail.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import mailgun from 'mailgun-js'
import log from '../lib/logger'
import {
APP_DOMAIN, ENVIRONMENT, MAIL_FROM, POSTMARK_KEY, MAILGUN_KEY
} from '../app/config'
} from '../server/app/config'

export default function sendMail({ to, subject, text }) {
log.info('sendMail attempt', { to, subject, text })
Expand Down
87 changes: 12 additions & 75 deletions app/api.js → server/api/v1/frontend.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,21 @@
import moment from 'moment-timezone'
import _ from 'lodash'
import { Router } from 'express'

import app from './express'
import { ALLOW_ADMIN_ACTIONS, APP_DOMAIN, ENVIRONMENT } from '../app/config'
import { Promises, Users } from '../models/'
import log, { deSequelize } from '../lib/logger'
import { diffPromises } from '../lib/parse/promise'
import actionNotifier from '../lib/notify'
import parseCredit from '../lib/parse/credit'
import { seed, importJson } from '../db/seed'
import cache from '../db/cache'

import { Promises, Users } from '../../models/'
import log, { deSequelize } from '../../../lib/logger'
import actionNotifier from '../../../lib/notify'
import parseCredit from '../../../lib/parse/credit'
import { diffPromises } from '../../../lib/parse/promise'

const userQuery = (user) => ({
model: Users,
where: { username: user }
})

const api = Router()

// Global endpoints

app.get('/users/create/:username', (req, res) => {
const { username } = req.params

if (username) {
Users.create({ username })
.then(() => {
log.info('user created', username)
res.redirect(`//${username}.${APP_DOMAIN}`)
})
} else {
res.redirect('/')
}
})


// User-scoped actions

// TODO implement a /create POST endpoint
// app.post('/promises/create/', (req, resp) => {})

app.post('/_s/:user/promises/edit', (req, res) => {
api.post('/_s/:user/promises/edit', (req, res) => {
// invalid dates/empty string values should unset db fields
const valOrNull = (val) => _.includes(['Invalid date', ''], val) ? null : val
const data = _.mapValues(req.body, (val) => valOrNull(val))
Expand Down Expand Up @@ -81,7 +56,7 @@ app.post('/_s/:user/promises/edit', (req, res) => {
})
})

app.post('/_s/:user/promises/complete', (req, resp) => {
api.post('/_s/:user/promises/complete', (req, resp) => {
Promises.findOne({
where: {
id: req.body.id
Expand All @@ -98,7 +73,7 @@ app.post('/_s/:user/promises/complete', (req, resp) => {
})
})

app.post('/_s/:user/promises/remove', (req, resp) => {
api.post('/_s/:user/promises/remove', (req, resp) => {
Promises.destroy({
where: {
id: req.body.id
Expand All @@ -114,9 +89,8 @@ app.post('/_s/:user/promises/remove', (req, resp) => {
})
})


// captcha
app.post('/_s/:user/promises/validate', ({ body: { id } = {} }, resp) => {
api.post('/_s/:user/promises/validate', ({ body: { id } = {} }, resp) => {
if (!id) {
resp.send(404)
} else {
Expand All @@ -128,41 +102,4 @@ app.post('/_s/:user/promises/validate', ({ body: { id } = {} }, resp) => {
}
})


// Utils

// calculate and store reliability for each user
app.get('/cache', (req, resp) => {
cache()
resp.redirect('/')
})

if (ENVIRONMENT !== 'production' || ALLOW_ADMIN_ACTIONS) {
// insert promises.json into db
app.get('/import', (req, resp) => {
importJson()
resp.redirect('/')
})

// drop db and repopulate
app.get('/reset', (req, resp) => {
seed()
resp.redirect('/')
})

// removes all entries from the promises table
app.get('/empty', (req, resp) => {
Promises.destroy({ where: {} })
resp.redirect('/')
})

// removes all promises for a given user
app.get('/_s/:user/promises/remove', function(req, resp) {
Promises.destroy({
include: [userQuery(req.params.user)],
}).then(function(deletedRows) {
log.warn('user promises removed', deletedRows)
resp.redirect('/')
})
})
}
export default api
83 changes: 83 additions & 0 deletions server/api/v1/promises.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { Router } from 'express'

import { Users } from '../../models/'
import log from '../../../lib/logger'
import { parsePromise, parsePromiseWithIp } from '../../../lib/parse/promise'

const api = Router()

api.post('/promises/parse/', (req, res) => {
const {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Identical blocks of code found in 2 locations. Consider refactoring.

promise = {},
urtext,
username,
timezone,
} = req.body

const parsedPromise = parsePromise({ promise, urtext, username, timezone })

if (!parsedPromise) {
resp.send(400)
} else {
res.send(parsedPromise)
}
})

api.post('/promises/create/', (req, res) => {
const {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Identical blocks of code found in 2 locations. Consider refactoring.

promise = {},
urtext,
username,
timezone,
} = req.body

const parsedPromise = parsePromise({ promise, urtext, username, timezone })

if (!parsedPromise) {
res.send(400)
} else {
Users.findOne({
where: {
username,
}
}).then(user => {
if (user) {
user.createPromise(parsedPromise)
.then(function(prom) {
log.info('promise created via POST', prom, req.body)
res.status(201).send(prom)
})
.catch((reason) => res.status(400).send(reason))
}
})
}
})

api.put('/promises/:username/:urtext', ({ ip, ...req }, res) => {
const {
urtext,
username,
} = req.params

Users.findOne({
where: {
username,
}
}).then(async(user) => {
if (user) {
const parsedPromise = await parsePromiseWithIp({ urtext, username, ip })

if (parsedPromise) {
user.createPromise(parsedPromise)
.then(function(prom) {
log.info('promise created via PUT', prom)
return res.status(201).send(prom)
})
.catch((reason) => res.status(400).send(reason))
}
}
return res.status(400)
})
})

export default api
23 changes: 23 additions & 0 deletions server/api/v1/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Router } from 'express'

import { Users } from '../../models/'
import log from '../../../lib/logger'
import { APP_DOMAIN } from '../../app/config'

const api = Router()

api.get('/users/create/:username', (req, res) => {
const { username } = req.params

if (username) {
Users.create({ username })
.then(() => {
log.info('user created', username)
res.redirect(`//${username}.${APP_DOMAIN}`)
})
} else {
res.redirect('/')
}
})

export default api
46 changes: 46 additions & 0 deletions server/app/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import app from './express'
import { ALLOW_ADMIN_ACTIONS, ENVIRONMENT } from '../app/config'
import { Promises } from '../models/'
import { seed, importJson } from '../db/seed'
import cache from '../db/cache'

import FrontendApi from '../api/v1/frontend'
import PromiseApi from '../api/v1/promises'
import UserApi from '../api/v1/users'

// TODO: https://github.com/Vincit/objection.js/tree/master/examples/express-ts
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO found


// Client-side/browser API
app.use('/', FrontendApi)

// "REST" endpoints
app.use('/_s/api/v1', PromiseApi)
app.use('/_s/api/v1', UserApi)

// Utils

// calculate and store reliability for each user
app.get('/cache', (req, resp) => {
cache()
resp.redirect('/')
})

if (ENVIRONMENT !== 'production' || ALLOW_ADMIN_ACTIONS) {
// insert promises.json into db
app.get('/import', (req, resp) => {
importJson()
resp.redirect('/')
})

// drop db and repopulate
app.get('/reset', (req, resp) => {
seed()
resp.redirect('/')
})

// removes all entries from the promises table
app.get('/empty', (req, resp) => {
Promises.destroy({ where: {} })
resp.redirect('/')
})
}
File renamed without changes.
10 changes: 4 additions & 6 deletions app/express.js → server/app/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ import expressHandlebars from 'express-handlebars'
import sassMiddleware from 'node-sass-middleware'
import useragent from 'express-useragent'

import '../../helpers'

import { PORT } from './config'
import log from '../lib/logger'
import '../helpers/calculate'
import '../helpers/colors'
import '../helpers/format'
import '../helpers/path'
import '../helpers/utils'
import log from '../../lib/logger'


const app = express()

Expand Down
File renamed without changes.
10 changes: 5 additions & 5 deletions app/middleware.js → server/app/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import _ from 'lodash'

import app from './express'
import { APP_DOMAIN } from '../app/config'
import log, { deSequelize } from '../lib/logger'
import actionNotifier from '../lib/notify'
import log, { deSequelize } from '../../lib/logger'
import actionNotifier from '../../lib/notify'
import { Promises, Users } from '../models'

import { parsePromise, parsePromiseWithIp } from '../lib/parse/promise'
import isValidUrl, { isBotFromUserAgent } from '../lib/parse/url'
import { nextCloseOfBusiness } from '../lib/parse/time'
import { parsePromise, parsePromiseWithIp } from '../../lib/parse/promise'
import isValidUrl, { isBotFromUserAgent } from '../../lib/parse/url'
import { nextCloseOfBusiness } from '../../lib/parse/time'

const pageWithStatus = ({
message, reason = {}, res = {}, template, status
Expand Down
Loading