From 6d2e54360030015326a3177ce739245772400084 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 10:36:15 +0100 Subject: [PATCH 01/16] added endpoint /thing/UUID/versions to retrieve all versions of a thing in a feature collection --- db/design_docs/journals.json | 3 ++ server/controllers/things/build_controller.js | 12 +++++ server/controllers/things/build_lib.js | 15 +++++++ server/controllers/things/things.js | 3 ++ test/integration/things.js | 45 +++++++++++++++++++ 5 files changed, 78 insertions(+) diff --git a/db/design_docs/journals.json b/db/design_docs/journals.json index 3c62449..79b440e 100644 --- a/db/design_docs/journals.json +++ b/db/design_docs/journals.json @@ -10,6 +10,9 @@ }, "byAttribute": { "map": "function(doc) {\n if (doc.context === 'journal' && doc.type === 'place' && doc.data && doc.data.properties && ( ! (doc.status && doc.status.deleted) ) ) {\n var lastVersionId = doc.versions.slice(-1)[0]\n const attributes = doc.data.properties\n for(key in attributes) {\n const value = attributes[key]\n emit([doc.type, key, value], {'_id': lastVersionId})\n }\n }\n}" + }, + "versionsById": { + "map": "function(doc) {\n if (doc.context === 'journal') {\n doc.versions.forEach( function(versionId) {\n emit([doc.type, doc._id], {'_id': versionId} )\n })\n }\n}" } } } diff --git a/server/controllers/things/build_controller.js b/server/controllers/things/build_controller.js index f6df333..8707188 100644 --- a/server/controllers/things/build_controller.js +++ b/server/controllers/things/build_controller.js @@ -24,6 +24,18 @@ module.exports = function (typeName) { .catch(error_.Handler(res)) } }, + getVersions: function (req, res) { + const id = req.params.id + + if (!_.isUuid(id)) { + error_.bundle(res, 'invalid id', 400, id) + return + } + + lib.versionsById(id) + .then(res.json.bind(res)) + .catch(error_.Handler(res)) + }, post: function (req, res) { lib.create(req.body) .then(res.json.bind(res)) diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index 99fce7e..c1f4140 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -75,6 +75,14 @@ module.exports = function (typeName, model) { .then(reject404) .then(Version.parseCurrentVersion) }, + versionsById: function (id) { + return db.viewByKeys('versionsById', [[typeName, id]]) + .then(_.Log('versionsById')) + .then(rejectEmptyCollection404) + .then(function (resultArray) { + return convertArrayToFeatureCollection(resultArray, typeName, `${id}/versions`) + }) + }, update: function (data, journalId) { // same as in create try { @@ -138,6 +146,13 @@ const reject404 = function (doc) { return doc } +const rejectEmptyCollection404 = function (doc) { + if(!(doc instanceof Array) || doc.length < 1) { + throw error_.new('no object with this id in db', 404, doc) + } + return doc +} + const updateJournal = function (data, journalId) { // create a new version associated to this journal return versions_.create(journalId, data) diff --git a/server/controllers/things/things.js b/server/controllers/things/things.js index a2ce6e0..60e7dfb 100644 --- a/server/controllers/things/things.js +++ b/server/controllers/things/things.js @@ -39,6 +39,9 @@ const typeRoutes = function (typeName) { put: controller.put, delete: controller.delete } + routes[`${typeName}/:id/versions`] = { + get: controller.getVersions + } return routes } diff --git a/test/integration/things.js b/test/integration/things.js index b38430c..acc1d3b 100644 --- a/test/integration/things.js +++ b/test/integration/things.js @@ -14,6 +14,23 @@ const delete_ = (url) => breq.delete(url).then(_.property('body')) const endpoint = CONFIG.server.url() + '/place' const placeNewDoc = require('../fixtures/place-new-to-create-for-api') +const createJournalWithTwoVersions = function (doc, callback) { + post(endpoint, doc) + .then(function (createResponse) { + get(`${endpoint}/${createResponse.id}`) + .then(function (firstVersion) { + doc.properties.name += ' - Version 2 ' + put(`${endpoint}/${firstVersion._id}`, doc) + .then(function (updateResponse) { + get(`${endpoint}/${updateResponse.id}`) + .then(function (secondVersion) { + callback(createResponse.id, firstVersion, secondVersion) + }) + }) + }) + }) +} + describe('/place', function () { describe('POST doc', function () { it('should return the doc with journal id', function (done) { @@ -60,6 +77,34 @@ describe('/place', function () { }) }) }) + describe('GET id/versions', function () { + it('should return a feature collection', function (done) { + createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { + get(`${endpoint}/${journalId}/versions`) + .then( function (versionsResponse) { + versionsResponse.type.should.equal('FeatureCollection') + done() + }) + }) + }) + it('should return all versions of that journal', function(done) { + createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { + get(`${endpoint}/${journalId}/versions`) + .then( function (versionsResponse) { + versionsResponse.features.length.should.equal(2) + done() + }) + }) + }) + it('should raise an error on non existing UUID', function(done) { + get(`${endpoint}/76100b453de20da6744eac86700294b8/versions`) + .then( _.Log('error response')) + .then( function (errorResponse) { + errorResponse.status.should.equal('no object with this id in db') + done() + }) + }) + }) describe('UPDATE id', function () { it('should accept a correct object for update', function (done) { post(endpoint, placeNewDoc) From 148a8d0190b3796ba169a86d3127d1fc613a7f34 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 10:37:24 +0100 Subject: [PATCH 02/16] Why didn't it take the changes? --- test/integration/things.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/integration/things.js b/test/integration/things.js index acc1d3b..7dff8db 100644 --- a/test/integration/things.js +++ b/test/integration/things.js @@ -81,25 +81,25 @@ describe('/place', function () { it('should return a feature collection', function (done) { createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { get(`${endpoint}/${journalId}/versions`) - .then( function (versionsResponse) { + .then(function (versionsResponse) { versionsResponse.type.should.equal('FeatureCollection') done() }) }) }) - it('should return all versions of that journal', function(done) { + it('should return all versions of that journal', function (done) { createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { get(`${endpoint}/${journalId}/versions`) - .then( function (versionsResponse) { + .then(function (versionsResponse) { versionsResponse.features.length.should.equal(2) done() }) }) }) - it('should raise an error on non existing UUID', function(done) { + it('should raise an error on non existing UUID', function (done) { get(`${endpoint}/76100b453de20da6744eac86700294b8/versions`) - .then( _.Log('error response')) - .then( function (errorResponse) { + .then(_.Log('error response')) + .then(function (errorResponse) { errorResponse.status.should.equal('no object with this id in db') done() }) From 6df1f3b58493c5e37eca4a104c9c28c62860f1a0 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 11:40:32 +0100 Subject: [PATCH 03/16] added _versionId to responses --- server/controllers/things/build_lib.js | 1 + server/controllers/things/models/commons/version.js | 1 + test/integration/things.js | 4 ++++ test/version-model.js | 9 ++++++++- 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index c1f4140..29d70c9 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -179,6 +179,7 @@ const convertArrayToFeatureCollection = function (data_array, item_type, query_s feature.properties._uri = hostname + '/' + item_type + '/' + item.journal feature.properties._timestamp = item.timestamp feature.properties._id = item.journal + feature.properties._verionId = item._id feature_collection.features.push(feature) }) return feature_collection diff --git a/server/controllers/things/models/commons/version.js b/server/controllers/things/models/commons/version.js index 499e68d..f64f2cc 100644 --- a/server/controllers/things/models/commons/version.js +++ b/server/controllers/things/models/commons/version.js @@ -28,6 +28,7 @@ const ThingVersion = { // faking to return the journal document id // while it's just the last version data._id = versionDoc.journal + data._versionId = versionDoc._id if(versionDoc.status && versionDoc.status.deleted === true) data._deleted = true diff --git a/test/integration/things.js b/test/integration/things.js index 7dff8db..7bfa120 100644 --- a/test/integration/things.js +++ b/test/integration/things.js @@ -65,6 +65,8 @@ describe('/place', function () { body2._id.should.equal(body1.id) // copying the id to make comparison simpler placeNewDoc._id = body2._id + // removing versionId to make comparison simpler + delete body2._versionId const b = JSON.stringify(placeNewDoc) const a = JSON.stringify(body2) if (a !== b) { @@ -148,6 +150,8 @@ describe('/place', function () { body3._id.should.equal(body2.id) // copying the id to make comparison simpler placeNewDoc._id = body3._id + // deleting the versionId to make comparison simpler + delete body3._versionId const b = JSON.stringify(placeNewDoc) const a = JSON.stringify(body3) a.should.equal(b) diff --git a/test/version-model.js b/test/version-model.js index 22a7409..5e1fbd5 100644 --- a/test/version-model.js +++ b/test/version-model.js @@ -62,7 +62,8 @@ describe('version model', function () { versionDoc.data = testdata const datastring = JSON.stringify(testdata) var retVal = Version.parseCurrentVersion(versionDoc) - delete retVal._id // only thing added by parseCurrentVersion on default + delete retVal._id // added by parseCurrentVersion on default + delete retVal._versionId // added by parseCurrentVersion on default const retValDataString = JSON.stringify(retVal) retValDataString.should.equal(datastring) done() @@ -73,6 +74,12 @@ describe('version model', function () { retVal._id.should.equal(someJournalId) done() }) + it('should add the versionId - atrribute according to the id of the versionDoc', function (done) { + const versionDoc = createValidVersionDoc(someJournalId) + const retVal = Version.parseCurrentVersion(versionDoc) + retVal._versionId.should.equal(versionDoc._id) + done() + }) it('should add the _deleted - flag if the deleted-status is set in the versionDoc', function (done) { var versionDoc = createValidVersionDoc(someJournalId) const status = { deleted: true, status2: 'blubb' } From 4bdaa530d9a89ef582d125d1c44e013d1ae2f3e0 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 13:21:56 +0100 Subject: [PATCH 04/16] endpoint /thing/uuid/version/versionUuid added --- db/design_docs/journals.json | 2 +- server/controllers/things/build_controller.js | 18 +++++ server/controllers/things/build_lib.js | 16 ++++- server/controllers/things/things.js | 3 + test/integration/things.js | 65 ++++++++++++++++++- 5 files changed, 101 insertions(+), 3 deletions(-) diff --git a/db/design_docs/journals.json b/db/design_docs/journals.json index 79b440e..f789ee8 100644 --- a/db/design_docs/journals.json +++ b/db/design_docs/journals.json @@ -12,7 +12,7 @@ "map": "function(doc) {\n if (doc.context === 'journal' && doc.type === 'place' && doc.data && doc.data.properties && ( ! (doc.status && doc.status.deleted) ) ) {\n var lastVersionId = doc.versions.slice(-1)[0]\n const attributes = doc.data.properties\n for(key in attributes) {\n const value = attributes[key]\n emit([doc.type, key, value], {'_id': lastVersionId})\n }\n }\n}" }, "versionsById": { - "map": "function(doc) {\n if (doc.context === 'journal') {\n doc.versions.forEach( function(versionId) {\n emit([doc.type, doc._id], {'_id': versionId} )\n })\n }\n}" + "map": "function(doc) {\n if (doc.context === 'journal') {\n doc.versions.forEach( function(versionId) {\n emit([doc.type, doc._id, versionId], {'_id': versionId} )\n })\n }\n}" } } } diff --git a/server/controllers/things/build_controller.js b/server/controllers/things/build_controller.js index 8707188..5cb4c68 100644 --- a/server/controllers/things/build_controller.js +++ b/server/controllers/things/build_controller.js @@ -36,6 +36,24 @@ module.exports = function (typeName) { .then(res.json.bind(res)) .catch(error_.Handler(res)) }, + getVersion: function (req, res) { + const id = req.params.id + const versionId = req.params.versionId + + if(!_.isUuid(id)) { + error_.bundle(res, 'invalid id', 400, id) + return + } + + if(!_.isUuid(versionId)) { + error_.bundle(res, 'invalid version id', 400, id) + return + } + + lib.versionById(id, versionId) + .then(res.json.bind(res)) + .catch(error_.Handler(res)) + }, post: function (req, res) { lib.create(req.body) .then(res.json.bind(res)) diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index 29d70c9..ca8e068 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -76,13 +76,27 @@ module.exports = function (typeName, model) { .then(Version.parseCurrentVersion) }, versionsById: function (id) { - return db.viewByKeys('versionsById', [[typeName, id]]) + const startKey = [typeName, id] + const endKey = [typeName, id, {}] + + return db.viewByKeyRange('versionsById', startKey, endKey) .then(_.Log('versionsById')) .then(rejectEmptyCollection404) .then(function (resultArray) { return convertArrayToFeatureCollection(resultArray, typeName, `${id}/versions`) }) }, + versionById: function (id, versionId) { + const startKey = [typeName, id, versionId] + const endKey = [typeName, id, versionId] + + return db.viewByKeyRange('versionsById', startKey, endKey) + .then(_.Log('viewByKeyRangeResult')) + .then(function (result) { return result[0] } ) + .then(_.Log('extractedItem')) + .then(reject404) + .then(Version.parseCurrentVersion) + }, update: function (data, journalId) { // same as in create try { diff --git a/server/controllers/things/things.js b/server/controllers/things/things.js index 60e7dfb..aaadb63 100644 --- a/server/controllers/things/things.js +++ b/server/controllers/things/things.js @@ -42,6 +42,9 @@ const typeRoutes = function (typeName) { routes[`${typeName}/:id/versions`] = { get: controller.getVersions } + routes[`${typeName}/:id/version/:versionId`] = { + get: controller.getVersion + } return routes } diff --git a/test/integration/things.js b/test/integration/things.js index 7bfa120..c7ce0c8 100644 --- a/test/integration/things.js +++ b/test/integration/things.js @@ -19,7 +19,7 @@ const createJournalWithTwoVersions = function (doc, callback) { .then(function (createResponse) { get(`${endpoint}/${createResponse.id}`) .then(function (firstVersion) { - doc.properties.name += ' - Version 2 ' + doc.properties.name += ' - Version 2' put(`${endpoint}/${firstVersion._id}`, doc) .then(function (updateResponse) { get(`${endpoint}/${updateResponse.id}`) @@ -107,6 +107,69 @@ describe('/place', function () { }) }) }) + describe('GET id/version/versionId', function () { + it('should return the version of id identifier by versionId', function (done) { + createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { + get(`${endpoint}/${journalId}/version/${firstVersion._versionId}`) + .then(function (versionGetResponse) { + firstVersion._versionId.should.equal(versionGetResponse._versionId) + JSON.stringify(firstVersion).should.equal(JSON.stringify(versionGetResponse)) + done() + }) + }) + }) + it('should not retreive the most recent version', function (done) { + createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { + get(`${endpoint}/${journalId}`) + .then(function (latestVersionResponse) { + get(`${endpoint}/${journalId}/version/${firstVersion._versionId}`) + .then(function (getVersionResponse) { + latestVersionResponse.properties.name + .should.equal(secondVersion.properties.name) + getVersionResponse.properties.name + .should.equal(firstVersion.properties.name) + done() + }) + }) + }) + }) + it('should return 400 for an invlaid id', function (done) { + breq.get(`${endpoint}/someInvalidId/version/someInvalidVersionId`) + .then(function (res) { + res.statusCode.should.equal(400) + res.body.status.should.equal('invalid id') + done() + }) + }) + it('should return 400 for an invalid version id', function (done) { + breq.get(`${endpoint}/76100b453de20da6744eac86700294b8/version/someInvalidVersionId`) + .then(function (res) { + res.statusCode.should.equal(400) + res.body.status.should.equal('invalid version id') + done() + }) + }) + it('should return 404 for an unknown id', function (done) { + createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { + breq.get(`${endpoint}/76100b453de20da6744eac86700294b8/version/${firstVersion._versionId}`) + .then(function (res) { + res.statusCode.should.equal(404) + res.body.status.should.equal('no object with this id in db') + done() + }) + }) + }) + it('should return 404 for an unknown versionId', function (done) { + createJournalWithTwoVersions(placeNewDoc, function (journalId, firstVersion, secondVersion) { + breq.get(`${endpoint}/${journalId}/version/76100b453de20da6744eac86700294b8`) + .then(function (res) { + res.statusCode.should.equal(404) + res.body.status.should.equal('no object with this id in db') + done() + }) + }) + }) + }) describe('UPDATE id', function () { it('should accept a correct object for update', function (done) { post(endpoint, placeNewDoc) From 34f2bc341c64337c433c7e09a24e45eb1e649b46 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 14:00:32 +0100 Subject: [PATCH 05/16] versionFeatureCollection now has correct URI --- server/controllers/things/build_lib.js | 27 ++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index ca8e068..2f2a1a3 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -83,7 +83,7 @@ module.exports = function (typeName, model) { .then(_.Log('versionsById')) .then(rejectEmptyCollection404) .then(function (resultArray) { - return convertArrayToFeatureCollection(resultArray, typeName, `${id}/versions`) + return convertArrayToVersionFeatureCollection(resultArray, typeName, `${id}/versions`) }) }, versionById: function (id, versionId) { @@ -157,7 +157,7 @@ const reject404 = function (doc) { if (!_.isPlainObject(doc)) { throw error_.new('no object with this id in db', 404, doc) } - return doc + return docType } const rejectEmptyCollection404 = function (doc) { @@ -198,3 +198,26 @@ const convertArrayToFeatureCollection = function (data_array, item_type, query_s }) return feature_collection } + +const convertArrayToVersionFeatureCollection = function(data_array, item_type, query_string) { + const hostname = 'https://data.transformap.co' + var feature_collection = { + 'type': 'FeatureCollection', + 'source': hostname + '/' + item_type + '/' + query_string, + 'license': 'Public Domain', + 'features': [] + } + + data_array.forEach( item => { + var feature = item.data + if(!feature.properties) + feature.properties = {} + feature.properties._uri = `${hostname}/${item_type}/${item.journal}/version/${item._id}` + feature.properties._timestamp = item.timestamp + feature.properties._id = item.journal + feature.properties._versionId = item._versionId + feature_collection.features.push(feature) + }) + + return feature_collection +} From 76f73146d9d713436234e6823656d081cd589ce3 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 14:19:44 +0100 Subject: [PATCH 06/16] drying up code --- server/controllers/things/build_lib.js | 50 +++++++++++--------------- 1 file changed, 20 insertions(+), 30 deletions(-) diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index 2f2a1a3..754dd45 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -15,8 +15,12 @@ module.exports = function (typeName, model) { .then(_.Log(`${typeName} byId`)) }, filter: function(filter_string) { + const uriBuilder = function (item, baseURI) { + return `${baseURI}/${item.journal}` + } + const convertArrayToTypeFeatureCollection = function (data_array) { - return convertArrayToFeatureCollection(data_array,typeName,filter_string) + return convertArrayToFeatureCollection(data_array,typeName,filter_string, uriBuilder) } if(filter_string == '') { return db.viewByKeyRange('currentVersionById', [typeName, '0'], [typeName, 'z']) @@ -76,15 +80,22 @@ module.exports = function (typeName, model) { .then(Version.parseCurrentVersion) }, versionsById: function (id) { + const uriBuilder = function (item, baseURI) { + return `${baseURI}/${item.journal}/version/${item._versionId}` + } + + const convertArrayToVersionTypeFeatureCollection = function (resultArray) { + return convertArrayToFeatureCollection(resultArray, typeName, `${id}/versions`, uriBuilder ) + } + const startKey = [typeName, id] const endKey = [typeName, id, {}] return db.viewByKeyRange('versionsById', startKey, endKey) .then(_.Log('versionsById')) .then(rejectEmptyCollection404) - .then(function (resultArray) { - return convertArrayToVersionFeatureCollection(resultArray, typeName, `${id}/versions`) - }) + .then(convertArrayToVersionTypeFeatureCollection) + .then(_.Log(`${typeName} versions for ${id}`)) }, versionById: function (id, versionId) { const startKey = [typeName, id, versionId] @@ -178,45 +189,24 @@ const updateJournal = function (data, journalId) { }) } -const convertArrayToFeatureCollection = function (data_array, item_type, query_string) { - const hostname = 'https://data.transformap.co' - var feature_collection = { - 'type': 'FeatureCollection', - 'source': hostname + '/' + item_type + '/' + query_string, - 'license': 'Public Domain', // only temporarly here - 'features': [] - } - data_array.forEach( item => { - var feature = item.data - if(!feature.properties) - feature.properties = {} - feature.properties._uri = hostname + '/' + item_type + '/' + item.journal - feature.properties._timestamp = item.timestamp - feature.properties._id = item.journal - feature.properties._verionId = item._id - feature_collection.features.push(feature) - }) - return feature_collection -} - -const convertArrayToVersionFeatureCollection = function(data_array, item_type, query_string) { +const convertArrayToFeatureCollection = function (data_array, item_type, query_string, uri_builder) { const hostname = 'https://data.transformap.co' var feature_collection = { 'type': 'FeatureCollection', - 'source': hostname + '/' + item_type + '/' + query_string, + 'source': `${hostname}/${item_type}/${query_string}`, 'license': 'Public Domain', 'features': [] } - data_array.forEach( item => { + feature_collection.features = data_array.map( item => { var feature = item.data if(!feature.properties) feature.properties = {} - feature.properties._uri = `${hostname}/${item_type}/${item.journal}/version/${item._id}` feature.properties._timestamp = item.timestamp feature.properties._id = item.journal feature.properties._versionId = item._versionId - feature_collection.features.push(feature) + feature.properties._uri = uri_builder(item, `${hostname}/${item_type}`) + return feature; }) return feature_collection From e20457ba7e463ec0197ea315554ecd5955aec68b Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 19:01:37 +0100 Subject: [PATCH 07/16] added /versions, /versions/:id, /versions/latest/:number --- db/design_docs/versions.json | 9 +- server/controllers/routes.js | 2 + server/controllers/things/build_lib.js | 2 +- server/controllers/versions/versions.js | 22 ++++ .../versions/versions_controller.js | 36 ++++++ server/controllers/versions/versions_lib.js | 72 ++++++++++++ server/lib/db/build_db_api.js | 24 +++- test/integration/versions.js | 111 ++++++++++++++++++ 8 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 server/controllers/versions/versions.js create mode 100644 server/controllers/versions/versions_controller.js create mode 100644 server/controllers/versions/versions_lib.js create mode 100644 test/integration/versions.js diff --git a/db/design_docs/versions.json b/db/design_docs/versions.json index 159bdea..7344b83 100644 --- a/db/design_docs/versions.json +++ b/db/design_docs/versions.json @@ -1,4 +1,9 @@ { "_id": "_design/versions", - "language": "javascript" -} \ No newline at end of file + "language": "javascript", + "views": { + "byTimestamp": { + "map": "function(doc) {\n if (doc.context === 'version') {\n emit(doc.timestamp, doc)\n }\n}" + } + } +} diff --git a/server/controllers/routes.js b/server/controllers/routes.js index 8e454cb..266c223 100644 --- a/server/controllers/routes.js +++ b/server/controllers/routes.js @@ -3,6 +3,7 @@ const __ = CONFIG.universalPath const _ = __.require('lib', 'utils') const things = require('./things/things') const root = require('./root/root') +const versions = require('./versions/versions') const routes = { 'hello': { @@ -14,6 +15,7 @@ const routes = { } _.extend(routes, things.generateRoutes()) +_.extend(routes, versions.generateRoutes()) _.extend(routes, root.generateHypermedia(routes)) module.exports = _.log(routes, 'routes') diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index 754dd45..d4d0849 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -168,7 +168,7 @@ const reject404 = function (doc) { if (!_.isPlainObject(doc)) { throw error_.new('no object with this id in db', 404, doc) } - return docType + return doc } const rejectEmptyCollection404 = function (doc) { diff --git a/server/controllers/versions/versions.js b/server/controllers/versions/versions.js new file mode 100644 index 0000000..f7f0653 --- /dev/null +++ b/server/controllers/versions/versions.js @@ -0,0 +1,22 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') + +const controller = require('./versions_controller') +const cntrlr = controller() + +module.exports = { + generateRoutes: function () { + return { + 'versions': { + get: cntrlr.all + }, + 'versions/:id': { + get: cntrlr.get + }, + 'versions/latest/:count': { + get: cntrlr.latest + } + } + } +} diff --git a/server/controllers/versions/versions_controller.js b/server/controllers/versions/versions_controller.js new file mode 100644 index 0000000..5e4cb7c --- /dev/null +++ b/server/controllers/versions/versions_controller.js @@ -0,0 +1,36 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') +const error_ = __.require('lib', 'error') + +const lib_ = require('./versions_lib') + +module.exports = function () { + const lib = lib_() + + return { + get: function (req, res) { + const id = req.params.id + + if(!_.isUuid(id)) { + error_.bundle(res, 'invalid id', 400, id) + return + } + + lib.byId(id) + .then(res.json.bind(res)) + .catch(error_.Handler(res)) + }, + all: function (req, res) { + lib.all() + .then(res.json.bind(res)) + .catch(error_.Handler(res)) + }, + latest: function (req, res) { + const count = req.params.count + lib.latest(count) + .then(res.json.bind(res)) + .then(error_.Handler(res)) + } + } +} diff --git a/server/controllers/versions/versions_lib.js b/server/controllers/versions/versions_lib.js new file mode 100644 index 0000000..6f9dcce --- /dev/null +++ b/server/controllers/versions/versions_lib.js @@ -0,0 +1,72 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') + +const db = __.require('lib', 'db/db')('things', 'versions') +const Version = require('../things/models/commons/version') + +module.exports = function () { + const uriBuilder = function (item, baseUri) { + return `${baseUri}/${item._versionId}` + } + const convertArrayToTypeFeatureCollection = function (data_array) { + return convertArrayToFeatureCollection(data_array, 'version', '', uriBuilder ) + } + + return { + byId: function (id) { + return db.get(id) + .then(_.Log('get')) + .then(reject404) + .then(Version.parseCurrentVersion) + }, + all: function () { + return db.viewDesc('byTimestamp') + .then(_.Log('byTimestamp')) + .then(convertArrayToTypeFeatureCollection) + }, + latest: function(count) { + return db.viewDescWithLimit('byTimestamp', count) + .then(_.Log(`byTimestamp with limit=${count}`)) + .then(convertArrayToTypeFeatureCollection) + } + + } +} + +const reject404 = function (doc) { + if (!_.isPlainObject(doc)) { + throw error_.new('no object with this id in db', 404, doc) + } + return doc +} + +const rejectEmptyCollection404 = function (doc) { + if(!(doc instanceof Array) || doc.length < 1) { + throw error_.new('no object with this id in db', 404, doc) + } + return doc +} + +const convertArrayToFeatureCollection = function (data_array, item_type, query_string, uri_builder) { + const hostname = 'https://data.transformap.co' + var feature_collection = { + 'type': 'FeatureCollection', + 'source': `${hostname}/${item_type}${query_string}`, + 'license': 'Public Domain', + 'features': [] + } + + feature_collection.features = data_array.map( item => { + var feature = item.data + if(!feature.properties) + feature.properties = {} + feature.properties._timestamp = item.timestamp + feature.properties._id = item.journal + feature.properties._versionId = item._versionId + feature.properties._uri = uri_builder(item, `${hostname}/${item_type}`) + return feature; + }) + + return feature_collection +} diff --git a/server/lib/db/build_db_api.js b/server/lib/db/build_db_api.js index 56c15cc..0b4fb83 100644 --- a/server/lib/db/build_db_api.js +++ b/server/lib/db/build_db_api.js @@ -32,6 +32,26 @@ module.exports = function (db, designName) { .then(parseNanoResponse) } + const viewDesc = function (viewName) { + return db.view(designName, viewName, { + include_docs: true, + descending: true + }) + .then(parseNanoResponse) + .then(parseDocs) + //.then(_.Log(`view ${designName} ${viewName}`)) + } + + const viewDescWithLimit = function (viewName, limit) { + return db.view(designName, viewName, { + include_docs: true, + descending: true, + limit: limit + }) + .then(parseNanoResponse) + .then(parseDocs) + } + return { get: get, post: insert, @@ -55,7 +75,9 @@ module.exports = function (db, designName) { .then(_.Log('viewByKey')) }, viewByKeys: viewByKeys, - viewByKeyRange: viewByKeyRange + viewByKeyRange: viewByKeyRange, + viewDesc: viewDesc, + viewDescWithLimit: viewDescWithLimit } } diff --git a/test/integration/versions.js b/test/integration/versions.js new file mode 100644 index 0000000..d286fd5 --- /dev/null +++ b/test/integration/versions.js @@ -0,0 +1,111 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') + +const it = global.it // for lint +const describe = global.describe // for lint +require('should') + +const breq = require('bluereq') +const get = (url) => breq.get(url).then(_.property('body')) +const post = (url, body) => breq.post(url, body).then(_.property('body')) +const placeEndpoint = CONFIG.server.url() + '/place' +const versionsEndpoint = CONFIG.server.url() + '/versions' +const placeNewDoc = require('../fixtures/place-new-to-create-for-api') + +const withCreatedVersion = function (template, lambda) { + post(placeEndpoint, placeNewDoc) + .then(function (body) { + get(`${placeEndpoint}/${body.id}`) + .then(function (doc) { + get(`${versionsEndpoint}/${doc._versionId}`) + .then(function (version) { + lambda(doc, version) + }) + }) + }) +} + +const withTwoVersions = function (lambda) { + post(placeEndpoint, placeNewDoc) + .then(function () { + post(placeEndpoint, placeNewDoc) + .then(function () { + lambda() + }) + }) +} + +describe('/versions', function () { + describe('GET', function () { + it('should return a feature collection', function (done) { + this.timeout(6000) // The request can become quite big + get(versionsEndpoint) + .then(function (result) { + result.type.should.equal('FeatureCollection') + done() + }) + }) + it('should list versions newest to oldest', function (done) { + this.timeout(6000)// The request can become quite big + post(placeEndpoint, placeNewDoc) + .then(function () { + post(placeEndpoint, placeNewDoc) + .then(function () { + get(versionsEndpoint) + .then(function (result) { + for (var i = 1; i < result.features.length; i++) { + result.features[i].properties._timestamp.should.be.belowOrEqual(result.features[i - 1].properties._timestamp) + } + done() + }) + }) + }) + }) + }) +}) + +describe('/versions/latest/:limit', function () { + it('should return a feature collection', function (done) { + get(`${versionsEndpoint}/latest/5`) + .then(function (result) { + result.type.should.equal('FeatureCollection') + done() + }) + }) + it('should list versions newest to oldest', function (done) { + withTwoVersions(function () { + get(`${versionsEndpoint}/latest/1`) + .then(function (result) { + result.features.length.should.be.belowOrEqual(5) + done() + }) + }) + }) +}) + +describe('/versions/:id', function () { + describe('GET', function () { + it('should be able to get a version', function (done) { + withCreatedVersion(placeNewDoc, function (thingObject, versionObject) { + thingObject._versionId.should.equal(versionObject._versionId) + done() + }) + }) + + it('should return 400 with invalid id', function (done) { + breq.get(`${versionsEndpoint}/someInvalidId`) + .then(function (res) { + res.statusCode.should.equal(400) + done() + }) + }) + it('should return 404 for unknown id', function (done) { + breq.get(`${versionsEndpoint}/76100b453de20da6744eac86700294b8`) + .then(function (res) { + res.statusCode.should.equal(404) + done() + }) + }) + }) +}) From 37ce65f6a97a7f376458a2619e59a2e993c3af3c Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 19:03:24 +0100 Subject: [PATCH 08/16] removed log output --- test/integration/things.js | 1 - 1 file changed, 1 deletion(-) diff --git a/test/integration/things.js b/test/integration/things.js index c7ce0c8..b243666 100644 --- a/test/integration/things.js +++ b/test/integration/things.js @@ -100,7 +100,6 @@ describe('/place', function () { }) it('should raise an error on non existing UUID', function (done) { get(`${endpoint}/76100b453de20da6744eac86700294b8/versions`) - .then(_.Log('error response')) .then(function (errorResponse) { errorResponse.status.should.equal('no object with this id in db') done() From c6df4c199c0d96d881598f08872cbd10f6f36255 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 20:03:31 +0100 Subject: [PATCH 09/16] added /versions/since/:pointInTime --- server/controllers/versions/versions.js | 3 ++ .../versions/versions_controller.js | 12 +++++++ server/controllers/versions/versions_lib.js | 6 ++++ server/lib/db/build_db_api.js | 7 ++-- test/integration/versions.js | 34 +++++++++++++++++++ 5 files changed, 59 insertions(+), 3 deletions(-) diff --git a/server/controllers/versions/versions.js b/server/controllers/versions/versions.js index f7f0653..611489b 100644 --- a/server/controllers/versions/versions.js +++ b/server/controllers/versions/versions.js @@ -16,6 +16,9 @@ module.exports = { }, 'versions/latest/:count': { get: cntrlr.latest + }, + 'versions/since/:pointInTime': { + get: cntrlr.latestSince } } } diff --git a/server/controllers/versions/versions_controller.js b/server/controllers/versions/versions_controller.js index 5e4cb7c..95af9bf 100644 --- a/server/controllers/versions/versions_controller.js +++ b/server/controllers/versions/versions_controller.js @@ -31,6 +31,18 @@ module.exports = function () { lib.latest(count) .then(res.json.bind(res)) .then(error_.Handler(res)) + }, + latestSince: function (req, res) { + const pointInTime = parseInt(req.params.pointInTime) + + if(isNaN(pointInTime)) { + error_.bundle(res, 'invalid point in time', 400, pointInTime) + return; + } + + lib.latestSince(pointInTime) + .then(res.json.bind(res)) + .then(error_.Handler(res)) } } } diff --git a/server/controllers/versions/versions_lib.js b/server/controllers/versions/versions_lib.js index 6f9dcce..96eeb5e 100644 --- a/server/controllers/versions/versions_lib.js +++ b/server/controllers/versions/versions_lib.js @@ -29,6 +29,12 @@ module.exports = function () { return db.viewDescWithLimit('byTimestamp', count) .then(_.Log(`byTimestamp with limit=${count}`)) .then(convertArrayToTypeFeatureCollection) + }, + latestSince: function(upTo) { + const now = (+ new Date()) + return db.viewByKeyRange('byTimestamp', upTo, now) + .then(_.Log(`byTimestamp since ${ new Date(upTo).toUTCString()}`)) + .then(convertArrayToTypeFeatureCollection) } } diff --git a/server/lib/db/build_db_api.js b/server/lib/db/build_db_api.js index 0b4fb83..868697c 100644 --- a/server/lib/db/build_db_api.js +++ b/server/lib/db/build_db_api.js @@ -12,15 +12,16 @@ module.exports = function (db, designName) { .then(parseDocs) .then(_.Log(`viewByKeys ${designName} ${viewName} ${keys}`)) } - const viewByKeyRange = function (viewName, startKey, endKey) { + const viewByKeyRange = function (viewName, startKey, endKey, desc = false) { return db.view(designName, viewName, { startkey: startKey, endkey: endKey, - include_docs: true + include_docs: true, + descending: desc }) .then(parseNanoResponse) .then(parseDocs) - .then(_.Log(`viewByKeyRange ${designName} ${viewName} ${startKey}-${endKey}`)) + .then(_.Log(`viewByKeyRange ${designName} ${viewName} ${startKey}-${endKey} descending - ${desc}`)) } const get = function (id) { diff --git a/test/integration/versions.js b/test/integration/versions.js index d286fd5..d2315de 100644 --- a/test/integration/versions.js +++ b/test/integration/versions.js @@ -109,3 +109,37 @@ describe('/versions/:id', function () { }) }) }) + +describe('/versions/since/:pointInTime', function () { + describe('GET', function () { + it('should return 400 with invalid point in time', function (done) { + breq.get(`${versionsEndpoint}/since/invalidPointInTime`) + .then(function (res) { + res.statusCode.should.equal(400) + done() + }) + }) + it('should return a feature collection', function (done) { + const pointInTime = (+new Date()) + withTwoVersions(function () { + get(`${versionsEndpoint}/since/${pointInTime}`) + .then(function (result) { + result.type.should.equal('FeatureCollection') + done() + }) + }) + }) + it('should return only versions with timestamp > pointInTime', function (done) { + const pointInTime = (+new Date()) + withTwoVersions(function () { + get(`${versionsEndpoint}/since/${pointInTime}`) + .then(function (result) { + result.features.forEach((feature) => { + feature.properties._timestamp.should.be.aboveOrEqual(pointInTime) + }) + done() + }) + }) + }) + }) +}) From e7829162f5a4d25f50dc42a14b466165acd0e50a Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 20:50:06 +0100 Subject: [PATCH 10/16] /versions/latest/:count now checks if :count is a number --- server/controllers/versions/versions_controller.js | 7 ++++++- test/integration/versions.js | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/server/controllers/versions/versions_controller.js b/server/controllers/versions/versions_controller.js index 95af9bf..a191c99 100644 --- a/server/controllers/versions/versions_controller.js +++ b/server/controllers/versions/versions_controller.js @@ -27,7 +27,12 @@ module.exports = function () { .catch(error_.Handler(res)) }, latest: function (req, res) { - const count = req.params.count + const count = parseInt(req.params.count) + if(isNaN(count)) { + error_.bundle(res, 'invalid count', 400, count) + return + } + lib.latest(count) .then(res.json.bind(res)) .then(error_.Handler(res)) diff --git a/test/integration/versions.js b/test/integration/versions.js index d2315de..b7b4ea4 100644 --- a/test/integration/versions.js +++ b/test/integration/versions.js @@ -82,6 +82,13 @@ describe('/versions/latest/:limit', function () { }) }) }) + it('should return 400 if :limit is not a number', function (done) { + breq.get(`${versionsEndpoint}/latest/notanumber`) + .then(function (res) { + res.statusCode.should.equal(400) + done() + }) + }) }) describe('/versions/:id', function () { From f31c6effd2896553771c95b3f04bb09a2bf14e25 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sat, 27 Jan 2018 20:50:32 +0100 Subject: [PATCH 11/16] added documentation for new and existing endpoints --- docs/api.md | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++ docs/index.md | 2 ++ 2 files changed, 80 insertions(+) create mode 100644 docs/api.md diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..2aa7ff7 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,78 @@ +# API documentation + +## `/things` +Currently there are two types of things: `place` and `raw`. To avoid duplication +I will only talk about `things`. They share the same endpoints. + +### `GET /things/:id` +This endpoint is used to retrieve things. `:id` can be: +- a UUID of a thing, which will provide the most recent version of that thing + - If the provided UUID is not found, `404` is returned + - If the provided `:id` is not a valid UUID, `400` is returned +- `all`, which will retreive all things currently available +- `property` or `property=`, which will retrieve all things that have a property +of that name +- `property=value`, which will retrieve all things that have the provided property +set to the provided value + +### `POST /things` +This endpoint is used to create a new thing. For `place`, the following conditions +have to be met for the place to be added to the database: +- The provided data needs to be valid geojson +- The provided data needs to have sane Coordinates - latitude between -90 and 90 degrees, +longitude between -180 and 180 degrees +- The provided data needs to have a property `name` with a nonempty string + +If any of there conditions are not met, `400` will be returned with an appropriate +error message + +Currently there are no limitations/validataions for `raw` things. + +### `PUT /things/:id` +This endpoint is used to update an existing thing. `:id` as to be a valid UUID. +The new version of the thing has to meet the same criteria as if it would be created. + +// TO BE CONTINUED + +### `DELETE /things/:id` +This endpoint is used to delete a thing. + +// TO BE CONTINUED + +### `GET /things/:id/versions` +This endpoint will return a `FeatureCollection` with all the known versions of that +thing. If `:id` is an invalid UUID, `400` is returned. If no thing can be found for +a valid UUID, `404` is returned. + +### `GET /things/:id/version/:versionId` +This endpoint will return a specific version of a thing. If either of the two +IDs is not a valid UUID `400` is returned. If neither `:id` nor `:versionId` can +be found, `404` is returned. + +Each thing has a property called `_versionId`, in case you wanted to know where +to get that id from. + +## `/versions` +Everytime a thing is updated it will not be changed in place, instead a new version +document will be created which will be linked to the Journal of that thing. The +`/versions` endpoints provide access to these. + +### `GET /versions` +Retrieves a `FeatureCollection` of all versions ever created. That one is a pretty +big request. + +### `GET /versions/:id` +Retrieves a specific version by id. Invalid UUID -> `400`, UUID not found -> `404` + +### `GET /versions/latest/:count` +Retrieves a `FeatureCollection` of the newest `:count` versions, chronologically sorted from newest to oldest. + +`:count` needs to be parseable into an integer. + +### `GET /versions/since/:pointInTime` +Retrieves a `FeatureCollection` of versions that were created since `:pointInTime`, +where `:pointInTime` needs to be a valid JavaScript timestamp. +The filtering is based on the `:_timestamp` property of each Version and `:pointInTime` +is an INCLUSIVE boundary. + +If `:pointInTime` can't be parsed to a number `400` will be returned. diff --git a/docs/index.md b/docs/index.md index 529fd00..1df12a3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,3 +1,5 @@ # data.transformap.co If you wish to install the daemon, please refer to the [installation documentation](/data.transformap.co/install) + +If you wish to find out more about the AP endpoints, please refer to the [API documentation](/data.transformatp.co/api) From 07888b7ca1bfd2b6b5e126302d0f6f99a032e5df Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sun, 28 Jan 2018 17:38:03 +0100 Subject: [PATCH 12/16] renaming to match original pattern --- ...{versions_controller.js => build_controller.js} | 4 ++-- .../versions/{versions_lib.js => build_lib.js} | 1 + server/controllers/versions/versions.js | 14 ++++++++------ 3 files changed, 11 insertions(+), 8 deletions(-) rename server/controllers/versions/{versions_controller.js => build_controller.js} (93%) rename server/controllers/versions/{versions_lib.js => build_lib.js} (99%) diff --git a/server/controllers/versions/versions_controller.js b/server/controllers/versions/build_controller.js similarity index 93% rename from server/controllers/versions/versions_controller.js rename to server/controllers/versions/build_controller.js index a191c99..d710dcf 100644 --- a/server/controllers/versions/versions_controller.js +++ b/server/controllers/versions/build_controller.js @@ -3,10 +3,10 @@ const __ = CONFIG.universalPath const _ = __.require('lib', 'utils') const error_ = __.require('lib', 'error') -const lib_ = require('./versions_lib') +const libraryBuilder = require('./build_lib') module.exports = function () { - const lib = lib_() + const lib = libraryBuilder() return { get: function (req, res) { diff --git a/server/controllers/versions/versions_lib.js b/server/controllers/versions/build_lib.js similarity index 99% rename from server/controllers/versions/versions_lib.js rename to server/controllers/versions/build_lib.js index 96eeb5e..653d073 100644 --- a/server/controllers/versions/versions_lib.js +++ b/server/controllers/versions/build_lib.js @@ -9,6 +9,7 @@ module.exports = function () { const uriBuilder = function (item, baseUri) { return `${baseUri}/${item._versionId}` } + const convertArrayToTypeFeatureCollection = function (data_array) { return convertArrayToFeatureCollection(data_array, 'version', '', uriBuilder ) } diff --git a/server/controllers/versions/versions.js b/server/controllers/versions/versions.js index 611489b..f2712a0 100644 --- a/server/controllers/versions/versions.js +++ b/server/controllers/versions/versions.js @@ -2,23 +2,25 @@ const CONFIG = require('config') const __ = CONFIG.universalPath const _ = __.require('lib', 'utils') -const controller = require('./versions_controller') -const cntrlr = controller() +const controllerBuilder = require('./build_controller') +const controller = controllerBuilder() module.exports = { + + generateRoutes: function () { return { 'versions': { - get: cntrlr.all + get: controller.all }, 'versions/:id': { - get: cntrlr.get + get: controller.get }, 'versions/latest/:count': { - get: cntrlr.latest + get: controller.latest }, 'versions/since/:pointInTime': { - get: cntrlr.latestSince + get: controller.latestSince } } } From ade70589a410347a884b36ae607aecde3bfef715 Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sun, 28 Jan 2018 18:25:20 +0100 Subject: [PATCH 13/16] extracted common behaviour --- server/controllers/lib_utils.js | 48 +++++++++++++++++++ server/controllers/things/build_lib.js | 59 +++++------------------- server/controllers/versions/build_lib.js | 46 ++---------------- 3 files changed, 65 insertions(+), 88 deletions(-) create mode 100644 server/controllers/lib_utils.js diff --git a/server/controllers/lib_utils.js b/server/controllers/lib_utils.js new file mode 100644 index 0000000..615cdb9 --- /dev/null +++ b/server/controllers/lib_utils.js @@ -0,0 +1,48 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') +const error_ = __.require('lib', 'error') + +module.exports = { + reject404: function (doc) { + if (!_.isPlainObject(doc)) { + throw error_.new('no object with this id in db', 404, doc) + } + + return doc + }, + + rejectEmptyCollection404: function (collection) { + if (!(collection instanceof Array) || collection.length < 1) { + throw error_.new('no object with this id in db', 404, collection) + } + + return collection + }, + + convertArrayToFeatureCollection: function (data_array, item_type, query_string, uri_builder) { + const hostname = 'https://data.transformap.co' + var feature_collection = { + 'type': 'FeatureCollection', + 'source': `${hostname}/${item_type}${query_string}`, + 'license': 'Public Domain', + 'features': [] + } + + feature_collection.features = data_array.map((item) => { + var feature = item.data + + if (!feature.properties) { + feature.properties = {} + } + feature.properties._timestamp = item.timestamp + feature.properties._id = item.journal + feature.properties._versionId = item._versionId + feature.properties._uri = uri_builder(item, hostname, item_type) + + return feature + }) + + return feature_collection + } +} diff --git a/server/controllers/things/build_lib.js b/server/controllers/things/build_lib.js index d4d0849..ff43dfa 100644 --- a/server/controllers/things/build_lib.js +++ b/server/controllers/things/build_lib.js @@ -7,6 +7,7 @@ const Version = require('./models/commons/version') const versions_ = require('./lib/versions') const promises_ = __.require('lib', 'promises') const error_ = __.require('lib', 'error') +const libUtils = require('../lib_utils.js') module.exports = function (typeName, model) { return { @@ -15,13 +16,14 @@ module.exports = function (typeName, model) { .then(_.Log(`${typeName} byId`)) }, filter: function(filter_string) { - const uriBuilder = function (item, baseURI) { - return `${baseURI}/${item.journal}` + const uriBuilder = function (item, hostname, item_type) { + return `${hostname}/${item_type}/${item.journal}` } const convertArrayToTypeFeatureCollection = function (data_array) { - return convertArrayToFeatureCollection(data_array,typeName,filter_string, uriBuilder) + return libUtils.convertArrayToFeatureCollection(data_array,typeName,`/${filter_string}`, uriBuilder) } + if(filter_string == '') { return db.viewByKeyRange('currentVersionById', [typeName, '0'], [typeName, 'z']) .then(convertArrayToTypeFeatureCollection) @@ -76,16 +78,16 @@ module.exports = function (typeName, model) { // return a document that doesn't belong to the required type return db.viewByKey('currentVersionById', [typeName, id]) .then(_.Log('currentVersionById')) - .then(reject404) + .then(libUtils.reject404) .then(Version.parseCurrentVersion) }, versionsById: function (id) { - const uriBuilder = function (item, baseURI) { - return `${baseURI}/${item.journal}/version/${item._versionId}` + const uriBuilder = function (item, hostname, item_type) { + return `${hostname}/${item_type}/${item.journal}/version/${item._versionId}` } const convertArrayToVersionTypeFeatureCollection = function (resultArray) { - return convertArrayToFeatureCollection(resultArray, typeName, `${id}/versions`, uriBuilder ) + return libUtils.convertArrayToFeatureCollection(resultArray, typeName, `/${id}/versions`, uriBuilder ) } const startKey = [typeName, id] @@ -93,7 +95,7 @@ module.exports = function (typeName, model) { return db.viewByKeyRange('versionsById', startKey, endKey) .then(_.Log('versionsById')) - .then(rejectEmptyCollection404) + .then(libUtils.rejectEmptyCollection404) .then(convertArrayToVersionTypeFeatureCollection) .then(_.Log(`${typeName} versions for ${id}`)) }, @@ -105,7 +107,7 @@ module.exports = function (typeName, model) { .then(_.Log('viewByKeyRangeResult')) .then(function (result) { return result[0] } ) .then(_.Log('extractedItem')) - .then(reject404) + .then(libUtils.reject404) .then(Version.parseCurrentVersion) }, update: function (data, journalId) { @@ -121,7 +123,7 @@ module.exports = function (typeName, model) { } return db.viewByKey('byId', [typeName, journalId]) // DB will return just 'undefined' if nothing is found - .then(reject404) + .then(libUtils.reject404) // Insert version object into journal. // journalId and data are already available // but we need to wait for the validation @@ -164,20 +166,6 @@ module.exports = function (typeName, model) { } } -const reject404 = function (doc) { - if (!_.isPlainObject(doc)) { - throw error_.new('no object with this id in db', 404, doc) - } - return doc -} - -const rejectEmptyCollection404 = function (doc) { - if(!(doc instanceof Array) || doc.length < 1) { - throw error_.new('no object with this id in db', 404, doc) - } - return doc -} - const updateJournal = function (data, journalId) { // create a new version associated to this journal return versions_.create(journalId, data) @@ -188,26 +176,3 @@ const updateJournal = function (data, journalId) { }) }) } - -const convertArrayToFeatureCollection = function (data_array, item_type, query_string, uri_builder) { - const hostname = 'https://data.transformap.co' - var feature_collection = { - 'type': 'FeatureCollection', - 'source': `${hostname}/${item_type}/${query_string}`, - 'license': 'Public Domain', - 'features': [] - } - - feature_collection.features = data_array.map( item => { - var feature = item.data - if(!feature.properties) - feature.properties = {} - feature.properties._timestamp = item.timestamp - feature.properties._id = item.journal - feature.properties._versionId = item._versionId - feature.properties._uri = uri_builder(item, `${hostname}/${item_type}`) - return feature; - }) - - return feature_collection -} diff --git a/server/controllers/versions/build_lib.js b/server/controllers/versions/build_lib.js index 653d073..aa95683 100644 --- a/server/controllers/versions/build_lib.js +++ b/server/controllers/versions/build_lib.js @@ -5,20 +5,22 @@ const _ = __.require('lib', 'utils') const db = __.require('lib', 'db/db')('things', 'versions') const Version = require('../things/models/commons/version') +const libUtils = require('../lib_utils') + module.exports = function () { const uriBuilder = function (item, baseUri) { return `${baseUri}/${item._versionId}` } - + const convertArrayToTypeFeatureCollection = function (data_array) { - return convertArrayToFeatureCollection(data_array, 'version', '', uriBuilder ) + return libUtils.convertArrayToFeatureCollection(data_array, 'version', '', uriBuilder ) } return { byId: function (id) { return db.get(id) .then(_.Log('get')) - .then(reject404) + .then(libUtils.reject404) .then(Version.parseCurrentVersion) }, all: function () { @@ -37,43 +39,5 @@ module.exports = function () { .then(_.Log(`byTimestamp since ${ new Date(upTo).toUTCString()}`)) .then(convertArrayToTypeFeatureCollection) } - - } -} - -const reject404 = function (doc) { - if (!_.isPlainObject(doc)) { - throw error_.new('no object with this id in db', 404, doc) - } - return doc -} - -const rejectEmptyCollection404 = function (doc) { - if(!(doc instanceof Array) || doc.length < 1) { - throw error_.new('no object with this id in db', 404, doc) } - return doc -} - -const convertArrayToFeatureCollection = function (data_array, item_type, query_string, uri_builder) { - const hostname = 'https://data.transformap.co' - var feature_collection = { - 'type': 'FeatureCollection', - 'source': `${hostname}/${item_type}${query_string}`, - 'license': 'Public Domain', - 'features': [] - } - - feature_collection.features = data_array.map( item => { - var feature = item.data - if(!feature.properties) - feature.properties = {} - feature.properties._timestamp = item.timestamp - feature.properties._id = item.journal - feature.properties._versionId = item._versionId - feature.properties._uri = uri_builder(item, `${hostname}/${item_type}`) - return feature; - }) - - return feature_collection } From c87de68636dbfc6e085de4f15da3148b34361f9e Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sun, 28 Jan 2018 18:27:48 +0100 Subject: [PATCH 14/16] handle rejection correctly --- server/controllers/versions/build_controller.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/controllers/versions/build_controller.js b/server/controllers/versions/build_controller.js index d710dcf..5a3bc21 100644 --- a/server/controllers/versions/build_controller.js +++ b/server/controllers/versions/build_controller.js @@ -35,7 +35,7 @@ module.exports = function () { lib.latest(count) .then(res.json.bind(res)) - .then(error_.Handler(res)) + .catch(error_.Handler(res)) }, latestSince: function (req, res) { const pointInTime = parseInt(req.params.pointInTime) @@ -47,7 +47,7 @@ module.exports = function () { lib.latestSince(pointInTime) .then(res.json.bind(res)) - .then(error_.Handler(res)) + .catch(error_.Handler(res)) } } } From c48c18cd80824ef9f81837a0c6d6bc460ed1f96b Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Sun, 28 Jan 2018 18:31:10 +0100 Subject: [PATCH 15/16] reorganized tests to reflect pattern that was present --- test/integration/versions.js | 61 ++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/test/integration/versions.js b/test/integration/versions.js index b7b4ea4..d53e64d 100644 --- a/test/integration/versions.js +++ b/test/integration/versions.js @@ -63,36 +63,7 @@ describe('/versions', function () { }) }) }) -}) - -describe('/versions/latest/:limit', function () { - it('should return a feature collection', function (done) { - get(`${versionsEndpoint}/latest/5`) - .then(function (result) { - result.type.should.equal('FeatureCollection') - done() - }) - }) - it('should list versions newest to oldest', function (done) { - withTwoVersions(function () { - get(`${versionsEndpoint}/latest/1`) - .then(function (result) { - result.features.length.should.be.belowOrEqual(5) - done() - }) - }) - }) - it('should return 400 if :limit is not a number', function (done) { - breq.get(`${versionsEndpoint}/latest/notanumber`) - .then(function (res) { - res.statusCode.should.equal(400) - done() - }) - }) -}) - -describe('/versions/:id', function () { - describe('GET', function () { + describe('GET id', function () { it('should be able to get a version', function (done) { withCreatedVersion(placeNewDoc, function (thingObject, versionObject) { thingObject._versionId.should.equal(versionObject._versionId) @@ -115,10 +86,32 @@ describe('/versions/:id', function () { }) }) }) -}) - -describe('/versions/since/:pointInTime', function () { - describe('GET', function () { + describe('GET latest/:limit', function () { + it('should return a feature collection', function (done) { + get(`${versionsEndpoint}/latest/5`) + .then(function (result) { + result.type.should.equal('FeatureCollection') + done() + }) + }) + it('should list versions newest to oldest', function (done) { + withTwoVersions(function () { + get(`${versionsEndpoint}/latest/1`) + .then(function (result) { + result.features.length.should.be.belowOrEqual(5) + done() + }) + }) + }) + it('should return 400 if :limit is not a number', function (done) { + breq.get(`${versionsEndpoint}/latest/notanumber`) + .then(function (res) { + res.statusCode.should.equal(400) + done() + }) + }) + }) + describe('GET since/:pointInTime', function () { it('should return 400 with invalid point in time', function (done) { breq.get(`${versionsEndpoint}/since/invalidPointInTime`) .then(function (res) { From e334298a9148a2e5365cb87a8be416c038cf022d Mon Sep 17 00:00:00 2001 From: ponder2342 Date: Mon, 29 Jan 2018 21:27:24 +0100 Subject: [PATCH 16/16] extended documentation --- docs/api.md | 224 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 181 insertions(+), 43 deletions(-) diff --git a/docs/api.md b/docs/api.md index 2aa7ff7..d39a0f9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,75 +1,213 @@ # API documentation -## `/things` -Currently there are two types of things: `place` and `raw`. To avoid duplication -I will only talk about `things`. They share the same endpoints. +## About Versions and Journals + +The database contains two kinds of Documents - journals and versions. +When you query for a point of interest by its UUID what you are actually +referring to is its Journal-ID. The journal itself holds an Array of UUIDs to +the versions associated with the journal. Here is an example of a journal +document: +``` +{ + "_id": "76100b453de20da6744eac8670000fc5", + "_rev": "4-874ae036f130f7b401fcb29f409b0cf4", + "context": "journal", + "type": "place", + "versions": [ + "76100b453de20da6744eac867000183c", + "76100b453de20da6744eac8670002061", + "76100b453de20da6744eac8670002c5a" + ], + "data": { + "type": "Feature", + "properties": { + "name": "The Name", + ... + } + } +} +``` + +And here is an example of a version document: +``` +{ + "_id": "76100b453de20da6744eac8670002c5a", + "_rev": "1-adb2c0c2185883dfcc67f670f78c5431", + "journal": "76100b453de20da6744eac8670000fc5", + "data": { + "type": "Feature", + "properties": { + "name": "test", + ... + }, + }, + "author": "Douglas Adams", + "description": "Have fun, and thanks for all the fish!", + "context": "version", + "timestamp": 1496915264158 +} +``` + +When a point of interest is changed, there are actually three things happening: +1. A new version document is created +2. The UUID of the new version document is added to the list of versions inside +the journal +3. The journals data attribute is set to the contents of the new version documents +data attribute + +## What you'll receive is neither. What you'll get, ... +What you will receive when querying the API are parts of version documents +What they will contain differs slightly whether or not you query for one or +multiple documents. + +### ... when you ask for a single document +To know what you receive when you query for only **one** document, you +have to take a look at +[the `parseCurrentVersion` method inside the version model](server/controllers/things/models/commons/version.js) +: +``` +parseCurrentVersion: function (versionDoc) { + const data = versionDoc.data + data._id = versionDoc.journal + data._versionId = versionDoc._id + + if(versionDoc.status && versionDoc.status.deleted === true) + data._deleted = true +} +``` +We just take the data object of the version doc, set its `_id` to the journals +UUID and add its own UUID as the `_versionId` attribute. + +### ... when you ask for multiple documents +To know what you receive when you query for multiple documents, you +have to take a look at +[the `convertArrayToFeatureCollection` method inside the lib_utils](server/controllers/lib_utils.js): + +First, we create the Skeleton of a Feture-Collection: +``` +var feature_collection = { + 'type': 'FeatureCollection', + 'source': `${hostname}/${item_type}${query_string}`, + 'license': 'Public Domain', + 'features': [] +} +``` + +Then we will build the features. Each feature is built out of the data attribute +of the version document, with a bit of meta data added (in this code snipped, +item refers to our version document): +``` +var feature = item.data + +if (!feature.properties) { + feature.properties = {} +} +feature.properties._timestamp = item.timestamp +feature.properties._id = item.journal +feature.properties._versionId = item._versionId +feature.properties._uri = uri_builder(item, hostname, item_type) + +return feature +``` + +## The API Endpoints + +Every time you query for more than one object a `FeatureCollection` will be +returned. + +### `/things` +Journals and versions describe things. Currently there are two types of things: +`place` and `raw`. To avoid duplication I will only talk about `things`. +They share the same endpoints. When I talk about an endpoint called +`/things/:id` I am actually talking about two endpoints - +one called `/place/:id`, the other `/raw/:id`. + +#### `GET /things/:id` +This endpoint is used to retrieve the most recent version of things, +where `:id` can be one of the following: -### `GET /things/:id` -This endpoint is used to retrieve things. `:id` can be: - a UUID of a thing, which will provide the most recent version of that thing - If the provided UUID is not found, `404` is returned - If the provided `:id` is not a valid UUID, `400` is returned -- `all`, which will retreive all things currently available +- `all`, which will retrieve all things currently available. This will include +things that are deleted. - `property` or `property=`, which will retrieve all things that have a property -of that name +of that name. This won't include deleted things. - `property=value`, which will retrieve all things that have the provided property -set to the provided value +set to the provided value. This won't include deleted things. -### `POST /things` -This endpoint is used to create a new thing. For `place`, the following conditions -have to be met for the place to be added to the database: +The result will not include things that are marked as deleted. + +#### `POST /things` +This endpoint is used to create a new thing. If successful, the id of the +created thing is returned. + +##### Valid data for places +If you try to create a thing via the `/place` route, your data has to meet the +following conditions: - The provided data needs to be valid geojson - The provided data needs to have sane Coordinates - latitude between -90 and 90 degrees, longitude between -180 and 180 degrees - The provided data needs to have a property `name` with a nonempty string -If any of there conditions are not met, `400` will be returned with an appropriate -error message +If any of these conditions isn't met, `400` will be returned with an appropriate +error message. + +##### Valid data for raw + +Currently there are no limitations/validations for `raw` things. -Currently there are no limitations/validataions for `raw` things. +#### `PUT /things/:id` +This endpoint is used to update an existing thing. To change a thing the new +version of the thing has to meet the same criteria as if you want to create it +and the API will react with the same answer: `400`, if the data you are sending +is not meeting the criteria. -### `PUT /things/:id` -This endpoint is used to update an existing thing. `:id` as to be a valid UUID. -The new version of the thing has to meet the same criteria as if it would be created. +If the UUID you've provided is a malformed, `400` will be returned. If the UUID +you've provided is not present, `404` will be returned. -// TO BE CONTINUED +If the update was successful, the new version of -### `DELETE /things/:id` -This endpoint is used to delete a thing. +#### `DELETE /things/:id` +This endpoint is used to mark a thing as deleted by adding a new version that +has `"status": { "deleted": true }` added to it. -// TO BE CONTINUED +If the provided UUID is not a valid UUID `400` will be returned. If nothing +can be found with the provided UUID `404` will be returned. If the thing you +are trying to delete is already deleted,`208` will be returned. -### `GET /things/:id/versions` -This endpoint will return a `FeatureCollection` with all the known versions of that -thing. If `:id` is an invalid UUID, `400` is returned. If no thing can be found for +If the deletion completes successfully, the full journal document of that poi + +#### `GET /things/:id/versions` +This endpoint will return all known versions of a thing identified by its UUID. + +If `:id` is an invalid UUID, `400` is returned. If no thing can be found for a valid UUID, `404` is returned. -### `GET /things/:id/version/:versionId` +#### `GET /things/:id/version/:versionId` This endpoint will return a specific version of a thing. If either of the two -IDs is not a valid UUID `400` is returned. If neither `:id` nor `:versionId` can -be found, `404` is returned. - -Each thing has a property called `_versionId`, in case you wanted to know where -to get that id from. +IDs is not a valid UUID `400` is returned. If either `:id` or `:versionId` +can't be found `404` will be returned. -## `/versions` -Everytime a thing is updated it will not be changed in place, instead a new version -document will be created which will be linked to the Journal of that thing. The -`/versions` endpoints provide access to these. +### `/versions` +With these Endpoints you can dig through the history of the data provided. +You will receive them in the same format as the most recent versions available +through the /things/id -### `GET /versions` -Retrieves a `FeatureCollection` of all versions ever created. That one is a pretty -big request. +#### `GET /versions` +This will give you all versions ever recorded. -### `GET /versions/:id` -Retrieves a specific version by id. Invalid UUID -> `400`, UUID not found -> `404` +#### `GET /versions/:id` +Retrieves a specific version identified by its id. -### `GET /versions/latest/:count` -Retrieves a `FeatureCollection` of the newest `:count` versions, chronologically sorted from newest to oldest. +#### `GET /versions/latest/:count` +Retrieves the newest `:count` versions, chronologically sorted from newest to +oldest. -`:count` needs to be parseable into an integer. +`:count` needs to be parseable into an integer. If it is not `400` will be +returned. -### `GET /versions/since/:pointInTime` +#### `GET /versions/since/:pointInTime` Retrieves a `FeatureCollection` of versions that were created since `:pointInTime`, where `:pointInTime` needs to be a valid JavaScript timestamp. The filtering is based on the `:_timestamp` property of each Version and `:pointInTime`