Skip to content

Commit 15e7de2

Browse files
committed
Implement read
1 parent e97c467 commit 15e7de2

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

index.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ const bodyParse = (req) => new Promise((resolve, reject) => {
6565
req.on('end', () => resolve(body ? JSON.parse(body) : {}))
6666
})
6767

68+
const noIdErr = () => JSON.stringify(new Error('no id passed'))
69+
6870
// exports
6971
module.exports = {register, start, logger, _find, _findAll, _create, _save}
7072

@@ -119,7 +121,11 @@ function handleRequest (req, res) {
119121
function logger () { return null }
120122

121123
// helper: find resource
122-
function _find () { return null }
124+
function _find (resource, id) {
125+
let attrs = {id_array: [id]}
126+
let firstRecord = (d) => Promise.resolve(d[0])
127+
return callPgFunc(`${pgPrefix}${resource}_read`, attrs).then(firstRecord)
128+
}
123129

124130
// helper: find set of resources
125131
function _findAll () { return null }
@@ -152,7 +158,14 @@ function resourceCreate (req, res, name) {
152158

153159
// resource method: read
154160
function resourceRead (req, res, name) {
155-
return res.end(`{"data": null, "error": null}`)
161+
if (!req.id && req.id !== 0) {
162+
return res.end(`{"data": null, "error": ${noIdErr()}}`)
163+
}
164+
_find(name, req.id).then((d) => {
165+
return res.end(`{"data": ${JSON.stringify(d)}, "error": null}`)
166+
}).catch((err) => {
167+
return res.end(`{"data": null, "error": ${JSON.stringify(err)}}`)
168+
})
156169
}
157170

158171
// resource method: update

test/index.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ test('scrud actions are handled as expected', async (assert) => {
2727
let s = await axios({method: 'GET', url: `${base}${sParams}`})
2828
assert.is(s.headers.scrud, 'member:search')
2929
let c = await axios({method: 'POST', url: `${base}`, data: postBody})
30+
let id = c.data.data.id
3031
assert.is(c.headers.scrud, 'member:create')
31-
let r = await axios({method: 'GET', url: `${base}/1`})
32+
let r = await axios({method: 'GET', url: `${base}/${id}`})
3233
assert.is(r.headers.scrud, 'member:read')
33-
let u = await axios({method: 'PUT', url: `${base}/1`})
34+
let u = await axios({method: 'PUT', url: `${base}/${id}`})
3435
assert.is(u.headers.scrud, 'member:update')
35-
let d = await axios({method: 'DELETE', url: `${base}/1`})
36+
let d = await axios({method: 'DELETE', url: `${base}/${id}`})
3637
assert.is(d.headers.scrud, 'member:delete')
3738
})
3839

0 commit comments

Comments
 (0)