Last active
December 24, 2015 16:19
-
-
Save garbados/6827007 to your computer and use it in GitHub Desktop.
Example of entity relations in a Cloudant design document.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| // name of the design doc | |
| _id: '_design/relations', | |
| views: { | |
| lib: couchapp.loadFiles(__dirname + '/../lib'), | |
| // collate entity relations using | |
| collate: { | |
| map: function (doc) { | |
| var deref = require('views/lib/index').deref, | |
| relation = deref[doc.type]; | |
| if (relation) { | |
| for (var key in relation) { | |
| emit([doc[key], relation[key], key], null); | |
| } | |
| } | |
| emit([doc._id, doc.type], null); | |
| }, | |
| reduce: '_count' | |
| } | |
| }, | |
| lists: { | |
| // indicates what items belong to which -- like a reverse JOIN | |
| belongs: function (head, req) { | |
| var results = {}, | |
| row; | |
| try { | |
| while (row = getRow()) { | |
| var id = row.key[0]; | |
| if (id === row.id) { | |
| results[id] = row.doc || row; | |
| } else { | |
| var rel = row.key[2]; | |
| // field = row.key[2]; | |
| if (!results[id]) { | |
| results[id] = {}; | |
| } | |
| if (!results[id][rel]) { | |
| results[id][rel] = []; | |
| } | |
| results[id][rel].push(row.doc || row); | |
| } | |
| } | |
| send(JSON.stringify(results)); | |
| } catch (e) { | |
| if (e.message === "row.key is null") { | |
| send('Request must not reduce results; disable reduce with `reduce=false` in the querystring.'); | |
| } else { | |
| send(JSON.stringify(e)); | |
| } | |
| } | |
| }, | |
| // object dereferencing; a JOIN equivalent | |
| owns: function (head, req) { | |
| var deref = require('views/lib/index').deref, | |
| results = {}, | |
| rows = [], | |
| row; | |
| try { | |
| while (row = getRow()) { | |
| rows.push(row); | |
| } | |
| rows.forEach(function (row) { | |
| if (row.key.length === 2) { | |
| results[row.id] = row.doc || row; | |
| } | |
| }); | |
| rows.forEach(function (row) { | |
| if (row.key.length === 3) { | |
| var target = row.key[0], | |
| field = row.key[2]; | |
| results[row.id][field] = results[target]; | |
| } | |
| }); | |
| send(JSON.stringify(results)); | |
| } catch (e) { | |
| if (e.message === "row.key is null") { | |
| send('Request must not reduce results; disable reduce with `reduce=false` in the querystring.'); | |
| } else if (e.message === "results[row.id] is undefined") { | |
| send('Request must contain all rows; don\'t use `key`, `keys`, `startkey`, and `endkey` as options for this list function.'); | |
| } else { | |
| send(JSON.stringify(e)); | |
| } | |
| } | |
| } | |
| }, | |
| shows: { | |
| // show code goes here | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment