Skip to content
This repository was archived by the owner on Jul 3, 2019. It is now read-only.

Commit b43af83

Browse files
committed
feat(read): add sync support for low-level content read
1 parent 8a94928 commit b43af83

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lib/content/read.js

+37
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,21 @@ function read (cache, integrity, opts) {
3333
})
3434
}
3535

36+
module.exports.sync = readSync
37+
function readSync (cache, integrity, opts) {
38+
opts = ReadOpts(opts)
39+
return withContentSriSync(cache, integrity, (cpath, sri) => {
40+
const data = fs.readFileSync(cpath)
41+
if (typeof opts.size === 'number' && opts.size !== data.length) {
42+
throw sizeError(opts.size, data.length)
43+
} else if (ssri.checkData(data, sri)) {
44+
return data
45+
} else {
46+
throw integrityError(sri, cpath)
47+
}
48+
})
49+
}
50+
3651
module.exports.stream = readStream
3752
module.exports.readStream = readStream
3853
function readStream (cache, integrity, opts) {
@@ -112,6 +127,28 @@ function withContentSri (cache, integrity, fn) {
112127
})
113128
}
114129

130+
function withContentSriSync (cache, integrity, fn) {
131+
const sri = ssri.parse(integrity)
132+
// If `integrity` has multiple entries, pick the first digest
133+
// with available local data.
134+
const algo = sri.pickAlgorithm()
135+
const digests = sri[algo]
136+
if (digests.length <= 1) {
137+
const cpath = contentPath(cache, digests[0])
138+
return fn(cpath, digests[0])
139+
} else {
140+
let lastErr = null
141+
for (const meta of sri[sri.pickAlgorithm()]) {
142+
try {
143+
return withContentSriSync(cache, meta, fn)
144+
} catch (err) {
145+
lastErr = err
146+
}
147+
}
148+
if (lastErr) { throw lastErr }
149+
}
150+
}
151+
115152
function sizeError (expected, found) {
116153
var err = new Error(Y`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
117154
err.expected = expected

test/content.read.js

+12
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,18 @@ test('read: returns a BB with cache content data', function (t) {
2929
})
3030
})
3131

32+
test('read.sync: reads synchronously', t => {
33+
const CONTENT = Buffer.from('foobarbaz')
34+
const INTEGRITY = ssri.fromData(CONTENT)
35+
const fixture = new Tacks(CacheContent({
36+
[INTEGRITY]: CONTENT
37+
}))
38+
fixture.create(CACHE)
39+
const data = read.sync(CACHE, INTEGRITY)
40+
t.deepEqual(data, CONTENT, 'cache contents read correctly')
41+
t.done()
42+
})
43+
3244
test('read.stream: returns a stream with cache content data', function (t) {
3345
const CONTENT = Buffer.from('foobarbaz')
3446
const INTEGRITY = ssri.fromData(CONTENT)

0 commit comments

Comments
 (0)