diff --git a/db/design_docs/journals.json b/db/design_docs/journals.json index 3c62449..f789ee8 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, versionId], {'_id': versionId} )\n })\n }\n}" } } } 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/docs/api.md b/docs/api.md new file mode 100644 index 0000000..d39a0f9 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,216 @@ +# API documentation + +## 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: + +- 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 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. This won't include deleted things. +- `property=value`, which will retrieve all things that have the provided property +set to the provided value. This won't include deleted things. + +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 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. + +#### `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. + +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. + +If the update was successful, the new version of + +#### `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. + +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. + +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` +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 either `:id` or `:versionId` +can't be found `404` will be returned. + +### `/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` +This will give you all versions ever recorded. + +#### `GET /versions/:id` +Retrieves a specific version identified by its id. + +#### `GET /versions/latest/:count` +Retrieves the newest `:count` versions, chronologically sorted from newest to +oldest. + +`:count` needs to be parseable into an integer. If it is not `400` will be +returned. + +#### `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) 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/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_controller.js b/server/controllers/things/build_controller.js index f6df333..5cb4c68 100644 --- a/server/controllers/things/build_controller.js +++ b/server/controllers/things/build_controller.js @@ -24,6 +24,36 @@ 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)) + }, + 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 99fce7e..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,9 +16,14 @@ module.exports = function (typeName, model) { .then(_.Log(`${typeName} byId`)) }, filter: function(filter_string) { + 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) + return libUtils.convertArrayToFeatureCollection(data_array,typeName,`/${filter_string}`, uriBuilder) } + if(filter_string == '') { return db.viewByKeyRange('currentVersionById', [typeName, '0'], [typeName, 'z']) .then(convertArrayToTypeFeatureCollection) @@ -72,7 +78,36 @@ 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, hostname, item_type) { + return `${hostname}/${item_type}/${item.journal}/version/${item._versionId}` + } + + const convertArrayToVersionTypeFeatureCollection = function (resultArray) { + return libUtils.convertArrayToFeatureCollection(resultArray, typeName, `/${id}/versions`, uriBuilder ) + } + + const startKey = [typeName, id] + const endKey = [typeName, id, {}] + + return db.viewByKeyRange('versionsById', startKey, endKey) + .then(_.Log('versionsById')) + .then(libUtils.rejectEmptyCollection404) + .then(convertArrayToVersionTypeFeatureCollection) + .then(_.Log(`${typeName} versions for ${id}`)) + }, + 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(libUtils.reject404) .then(Version.parseCurrentVersion) }, update: function (data, journalId) { @@ -88,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 @@ -131,13 +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 updateJournal = function (data, journalId) { // create a new version associated to this journal return versions_.create(journalId, data) @@ -148,23 +176,3 @@ 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_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/server/controllers/things/things.js b/server/controllers/things/things.js index a2ce6e0..aaadb63 100644 --- a/server/controllers/things/things.js +++ b/server/controllers/things/things.js @@ -39,6 +39,12 @@ const typeRoutes = function (typeName) { put: controller.put, delete: controller.delete } + routes[`${typeName}/:id/versions`] = { + get: controller.getVersions + } + routes[`${typeName}/:id/version/:versionId`] = { + get: controller.getVersion + } return routes } diff --git a/server/controllers/versions/build_controller.js b/server/controllers/versions/build_controller.js new file mode 100644 index 0000000..5a3bc21 --- /dev/null +++ b/server/controllers/versions/build_controller.js @@ -0,0 +1,53 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') +const error_ = __.require('lib', 'error') + +const libraryBuilder = require('./build_lib') + +module.exports = function () { + const lib = libraryBuilder() + + 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 = parseInt(req.params.count) + if(isNaN(count)) { + error_.bundle(res, 'invalid count', 400, count) + return + } + + lib.latest(count) + .then(res.json.bind(res)) + .catch(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)) + .catch(error_.Handler(res)) + } + } +} diff --git a/server/controllers/versions/build_lib.js b/server/controllers/versions/build_lib.js new file mode 100644 index 0000000..aa95683 --- /dev/null +++ b/server/controllers/versions/build_lib.js @@ -0,0 +1,43 @@ +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') + +const libUtils = require('../lib_utils') + +module.exports = function () { + const uriBuilder = function (item, baseUri) { + return `${baseUri}/${item._versionId}` + } + + const convertArrayToTypeFeatureCollection = function (data_array) { + return libUtils.convertArrayToFeatureCollection(data_array, 'version', '', uriBuilder ) + } + + return { + byId: function (id) { + return db.get(id) + .then(_.Log('get')) + .then(libUtils.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) + }, + 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/controllers/versions/versions.js b/server/controllers/versions/versions.js new file mode 100644 index 0000000..f2712a0 --- /dev/null +++ b/server/controllers/versions/versions.js @@ -0,0 +1,27 @@ +const CONFIG = require('config') +const __ = CONFIG.universalPath +const _ = __.require('lib', 'utils') + +const controllerBuilder = require('./build_controller') +const controller = controllerBuilder() + +module.exports = { + + + generateRoutes: function () { + return { + 'versions': { + get: controller.all + }, + 'versions/:id': { + get: controller.get + }, + 'versions/latest/:count': { + get: controller.latest + }, + 'versions/since/:pointInTime': { + get: controller.latestSince + } + } + } +} diff --git a/server/lib/db/build_db_api.js b/server/lib/db/build_db_api.js index 56c15cc..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) { @@ -32,6 +33,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 +76,9 @@ module.exports = function (db, designName) { .then(_.Log('viewByKey')) }, viewByKeys: viewByKeys, - viewByKeyRange: viewByKeyRange + viewByKeyRange: viewByKeyRange, + viewDesc: viewDesc, + viewDescWithLimit: viewDescWithLimit } } diff --git a/test/integration/things.js b/test/integration/things.js index b38430c..b243666 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) { @@ -48,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) { @@ -60,6 +79,96 @@ 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(function (errorResponse) { + errorResponse.status.should.equal('no object with this id in db') + done() + }) + }) + }) + 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) @@ -103,6 +212,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/integration/versions.js b/test/integration/versions.js new file mode 100644 index 0000000..d53e64d --- /dev/null +++ b/test/integration/versions.js @@ -0,0 +1,145 @@ +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('GET id', 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() + }) + }) + }) + 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) { + 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() + }) + }) + }) + }) +}) 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' }