Skip to content

Commit

Permalink
update users handlers
Browse files Browse the repository at this point in the history
ref #10
  • Loading branch information
maxgrossman committed Aug 6, 2018
1 parent 7e21014 commit f542572
Show file tree
Hide file tree
Showing 23 changed files with 271 additions and 2,426 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ testData/
.python_version
.vscode
node_modules/
yarn-error.log
8 changes: 6 additions & 2 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@

module.exports = {
test: {
db: './db/test-posm-paths.sqlite3'
db: './db/test-posm-paths.sqlite3',
host: 'localhost',
injectDefaults: { simulate: { error: false }}
},
develop: {
db: './db/posm-paths.sqlite3'
db: './db/posm-paths.sqlite3',
host: 'localhost',
injectDefaults: { simulate: { error: false }}
}
}
44 changes: 43 additions & 1 deletion db/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
'use strict';

const sqlite3 = require('sqlite3').verbose();;
const config = require('../config');
const uuidv4 = require('uuid/v4');

Promise = require('bluebird');

class Database {
Expand Down Expand Up @@ -51,6 +54,45 @@ class Database {
.then(() => this.select(sql))
.catch((err) => { throw err; });
}
addUsers(...users) {
users = users.map(user => `('${uuidv4()}', '${user}')`).join(',')
const sql = `INSERT INTO Users VALUES ${users};`
return this
.execute(sql)
.then((result) => result)
.catch((err) => { throw err; });

}
addImages(userId, sequenceId, images) {
images = images.map((image, index) => {
return `(
'${image.id}',
'${image.image}',
'${image.timestamp}',
'${index}',
'${sequenceId}',
'${userId}',
GeomFromText('POINT(${image.loc.lat} ${image.loc.lon})', 4326)
)`
}).join(',');
const sql = `INSERT INTO Images VALUES ${images}`;
return this
.executeSpatial(sql)
.then((result) => result)
.catch((err) => { throw err; })
}
addSequence(userId, imageIds) {
const values = `(
'${uuidv4()}',
'${userId}',
json('${JSON.stringify(imageIds)}')
)`;
const sql = `INSERT INTO Sequences VALUES ${values};`;
return this
.execute(sql)
.then((result) => result)
.catch((err) => { throw err; })
}
};

const instance = new Database();
Expand Down
30 changes: 0 additions & 30 deletions db/migrations/1533377095426-add-sequences.js

This file was deleted.

43 changes: 30 additions & 13 deletions db/seeds/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,37 @@ const Database = require('../');

Database.connect(dbLoc);

let seeds = [
{
users: () => {
const values = users.map(user => `('${uuidv4()}', '${user.name}')`).join(',');
const sql = `INSERT INTO Users VALUES ${values};`;
return Database.execute(sql)
.catch((err) => { throw err; });
}
}
];
const userId = users[0].id
const imageIds = [...Array(5).keys()].map(k => uuidv4());

if (process.argv.slice(2).length > 0) {
seeds = seeds.filter(s => process.argv.includes(Object.keys(s)[0]));
let seeds = {
users: () => {
const values = users.map(user => `('${user.id}', '${user.name}')`).join(',');
const sql = `INSERT INTO Users VALUES ${values};`;
return Database
.execute(sql)
.catch((err) => { throw err; });
},
images: () => {
const images = imageIds.map((id, index) => {
return {
id: id,
image:'.',
timestamp: (new Date()).toISOString(),
index: index,
loc: {
lat: Math.floor(Math.random() * Math.floor(10)),
lon: Math.floor(Math.random() * Math.floor(10))
}
}
})
return Database
.addImages(userId, uuidv4(), images)
.catch((err) => { throw err; })
}
}

seeds.forEach(s => Object.values(s)[0]());
Object
.values(seeds)
.forEach(async (seed) => await seed().catch(err => { console.error(err) ; }))

1 change: 0 additions & 1 deletion db/sql/1533377095426-add-sequences-down.sql

This file was deleted.

6 changes: 0 additions & 6 deletions db/sql/1533377095426-add-sequences-up.sql

This file was deleted.

34 changes: 7 additions & 27 deletions handlers/sequence/helpers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

const db = require('../../connection');
const fs = require('fs-extra');
const Database = require('../../db');

/**
* Provided parameters for a sequence and its images,
Expand All @@ -13,11 +12,10 @@ exports.insertImagesSequence = async (sequenceMap) => {
const sequenceId = sequenceMap.sequenceId,
userId = sequenceMap.userId;

let imageInserts = [],
imageFeatures = [];
let images = [];

sequenceMap.sequence.forEach((image, index) => {
imageInserts.push(`
images.push(`
INSERT INTO Images (
id, path, time, seqIdx, seqId, userId, loc
) VALUES (
Expand All @@ -30,29 +28,11 @@ exports.insertImagesSequence = async (sequenceMap) => {
GeomFromText('POINT(${image.loc.lat} ${image.loc.lon})', 4326)
);`
);
imageFeatures.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [image.loc.lon, image.loc.lat]
},
properties: { id: image.id }
})
});
})

db.raw(`
INSERT INTO Sequences (
id, userId, images
) VALUES (
'${sequenceId}',
'${userId}',
json('${JSON.stringify(imageFeatures)}')
);
SELECT load_extension("mod_spatialite");
${imageInserts}
`)
.then((res) => {console.log(res)})
.then((error) => {console.error(error)})
Database.insertImages(images)
.then((res) => {consoleo(res)})
.then((error) => {console.error(error)})

} catch (error) {
console.error(error);
Expand Down
18 changes: 9 additions & 9 deletions handlers/user/get.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
'use strict';

const Boom = require('boom');
const db = require('../../connection');
const uuidv4 = require('uuid/v4');
const Database = require('../../db');
const databaseLocation = require('../../config')[process.env.ENVIRONMENT || 'develop'].db;

module.exports = async (r, h) => {
try {
const id = r.params.id,
ids = (await db('Users').select('id')).map(user => user.id);
Database.connect(databaseLocation);
const id = r.params.id;
const users = await Database.select(`SELECT name FROM Users WHERE id='${id}'`);

if (ids.indexOf(id) === -1) {
if (users.length === 0) {
return Boom.badRequest('User not in database')
}


const user = (await db('Users').select('name').where({id: id}))[0];

return h.response({ upload: 'successful', name: user.name }).code(200)
Database.close();

return h.response({ upload: 'successful', name: users[0].name }).code(200)

} catch (error) {
console.error(error);
Expand Down
16 changes: 10 additions & 6 deletions handlers/user/post.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
'use strict';

const Boom = require('boom');
const db = require('../../connection');
const uuidv4 = require('uuid/v4');
const databaseLocation = require('../../config')[process.env.ENVIRONMENT || 'develop'].db;
const Database = require('../../db');

module.exports = async (r, h) => {
try {
const userName = r.payload.name,
users = (await db('Users').select('name')).map(user => user.name);
Database.connect(databaseLocation);

const userName = r.payload.name
const users = await Database.select('SELECT name FROM Users');

if (users.indexOf(userName) > -1) {
if (users.map(user => user.name).indexOf(userName) > -1) {
return Boom.badRequest('user already exists');
}

await db('Users').insert({id: uuidv4(), name: userName});
await Database.addUsers(userName)
Database.close()

return h.response({ upload: 'successful' }).code(200)

} catch (error) {
Expand Down
21 changes: 21 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

const Hapi = require('hapi');
const routes = require('./routes');

const server = Hapi.server({
port: process.env.PORT || 3000,
host: process.env.HOST || 'localhost'
});

const initServer = async () => {
await server.register(require('inert'));
server.route(routes)
}

process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
})

initServer();
34 changes: 34 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
"author": "Max Grossman <[email protected]>",
"license": "MIT",
"scripts": {
"clean-migrations": "rm -f db/test-posm-paths.sqlite3 && rm -f db/posm-paths.sqlite3 && rm -f db/migrations/.migrate",
"test": "mocha test/**/* --exit",
"test:db": "mocha test/db.js",
"test:migrate": "npm run migrate:up:seed && npm run test:db",
"migrate:clean": "rm -f db/test-posm-paths.sqlite3 && rm -f db/posm-paths.sqlite3 && rm -f db/migrations/.migrate",
"migrate:up": "./node_modules/.bin/migrate up --state-file db/migrations/.migrate --migrations-dir db/migrations",
"migrate:down": "migrate down --state-file db/migrations/.migrate --migrations-dir db/migrations",
"seed": "node db/seeds/index.js",
Expand All @@ -23,6 +23,7 @@
"exiftool-vendored": "^4.22.1",
"fs-extra": "^5.0.0",
"hapi": "^17.4.0",
"inert": "^5.1.0",
"joi": "^13.2.0",
"knex": "^0.14.6",
"migrate": "^1.6.0",
Expand Down
5 changes: 5 additions & 0 deletions schema/uuid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

const Joi = require('joi');

module.exports = Joi.string().regex(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
Loading

0 comments on commit f542572

Please sign in to comment.