diff --git a/app/controllers/PublicStateController.js b/app/controllers/PublicStateController.js new file mode 100644 index 0000000..beb21c5 --- /dev/null +++ b/app/controllers/PublicStateController.js @@ -0,0 +1,50 @@ +const { v4: uuidv4 } = require('uuid'); + +class PublicStateController { + + constructor(database) { + this.database = database; + }; + + create(data, user, onSuccess, onError) { + console.log('PublicStateController.create'); + let collection = this.database.collection('publicStates'); + collection.findOne({name: data.name}, {}, (dbErr, dbRes) => { + if (dbErr === null) { + if (dbRes === null) { + let title = data.tile | data.name; + let pubState = { + id: uuidv4(), + name: data.name, + title: title, + createdBy: user.id, + ts: new Date().getTime(), + v: 1 + }; + collection.insertOne(pubState, (insertErr, insertRes) => { + if (insertErr === null) { + onSuccess(pubState); + } else { + onError({ + error: 'database error: could not create public state', + message: insertErr.message + }) + } + }); + } else { + onError({ + code: 'app error', + message: 'a public state with that name already exists' + }); + } + } else { + onError({ + code: 'database error', + message: dbErr.message + }); + } + }); + }; +}; + +module.exports = PublicStateController; diff --git a/app/routes/api.js b/app/routes/api.js index 0995e68..a700094 100644 --- a/app/routes/api.js +++ b/app/routes/api.js @@ -1,13 +1,38 @@ const express = require('express'); const router = express.Router(); -const UserController = require('../controllers/UserController'); const Authenticator = require('../Authenticator'); +const UserController = require('../controllers/UserController'); +const PublicStateController = require('../controllers/PublicStateController'); router.get('/', function (req, res, next) { let rnd = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5); res.send('respond with some api calls - ' + rnd); }); +router.post('/state', (req, res, next) => { + app = req.app; + db = app.locals.database; + + let authenticator = new Authenticator(db); + let ctrl = new PublicStateController(db); + + let scb = (data) => { + res.json(data); + }; + + let ecb = (error) => { + res.status(400).send(err); + }; + + authenticator.getAuthenticatedUser(req, (user) => { + if (user) { + ctrl.create(req.body, scb, ecb); + } else { + ecb({ code: 'auth error', message: 'user not logged in.' }); + } + }); +}); + router.get('/user', function (req, res, next) { app = req.app; db = app.locals.database; @@ -27,7 +52,7 @@ router.get('/user', function (req, res, next) { if (user) { ctrl.getUserData(user, scb, ecb); } else { - ecb({ code: 'app error', message: 'user not logged in.' }); + ecb({ code: 'auth error', message: 'user not logged in.' }); } }); });