Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @author Mike Hamilton <mike@mikehamilton.ca>
- * @copyright Mike Hamilton 2017
- * @license MIT
- *
- * @requires koa@next
- * @requires koa-router
- * @requires pg
- * @requires knex
- * @requires knex-postgis
- */
- const Koa = require('koa')
- const app = new Koa()
- const Router = require('koa-router')
- const router = new Router({
- prefix: '/hydrant'
- })
- // REQUIRE PostGRES module
- var pg = require('pg')
- // REQUIRE knex + setup
- var knex = require('knex')({
- dialect: 'postgres',
- client: 'pg',
- connection: {
- host: 'wbsnowmaking.com',
- user: 'xxx',
- password: 'xxxx',
- database: 'whistlerblackcomb'
- },
- pool: {
- min: 0,
- max: 7
- }
- })
- // REQUIRE knex-postgis (PostGRES extension)
- var st = require('knex-postgis')(knex);
- /**
- * @desc Function to return single element
- * @param {number} id
- * @param {string} table
- * @param {string} schema
- * @param {number} srid
- */
- async function getSingle(id, table, schema, srid) {
- return await knex
- .withSchema(schema)
- .from(table)
- .where({
- id: id
- })
- .select(
- '*',
- st.y(st.transform('geom', srid)).as('lat_gen'),
- st.x(st.transform('geom', srid)).as('lon_gen')
- )
- }
- /**
- * @desc Function to return all elements
- * @param {string} table
- * @param {string} schema
- * @param {number} srid
- */
- async function getAll(table, schema, srid) {
- return await knex
- .withSchema(schema)
- .select(
- '*',
- st.y(st.transform('geom', srid)).as('lat_gen'),
- st.x(st.transform('geom', srid)).as('lon_gen')
- )
- .from(table)
- }
- /**
- * @desc Function to delete single element
- * @param {number} id
- * @param {string} table
- * @param {string} schema
- */
- async function delSingle(id, table, schema) {
- return await knex
- .withSchema(schema)
- .where({
- id: id
- })
- .del()
- .from(table)
- }
- router
- // (C)reate
- .put('/', async ctx => {
- ctx.body = JSON.stringify('Create')
- })
- // (R)ead All
- .get('/', async ctx => {
- ctx.body = await getAll('hydrants', 'snowmaking', '4326')
- })
- // (R)ead Single
- .get('/:id', async (ctx, next) => {
- try {
- response = await getSingle(ctx.params.id, 'hydrants', 'snowmaking', '4326')
- if (response == '') {
- return ctx.status = 404
- } else {
- return ctx.body = response
- }
- } catch (err) {
- ctx.status = err.status || 500
- ctx.body = JSON.stringify('Oh dear, something seems to have gone wrong.')
- ctx.app.emit('error', err, ctx)
- }
- })
- // (U)pdate
- .patch('/:id', async ctx => {
- ctx.body = JSON.stringify('Update')
- })
- // (D)elete
- .delete('/:id', async ctx => {
- ctx.body = JSON.stringify('Delete')
- })
- app
- .use(router.routes())
- .use(router.allowedMethods())
- app.listen(3000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement