Skip to content

Commit 337d3b6

Browse files
committed
handle stream error
1 parent 65ada54 commit 337d3b6

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/index.test.ts

+27-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as mockSiteModel from './test-helpers/mock-site-model.json';
77
import { createMockKoopApp } from './test-helpers/create-mock-koop-app';
88
import { readableFromArray } from './test-helpers/stream-utils';
99
import { DcatUsError } from './dcat-us/dcat-us-error';
10+
import { PassThrough } from 'stream';
1011

1112
function buildPluginAndApp(feedTemplate, feedTemplateTransforms) {
1213
let Output;
@@ -21,9 +22,16 @@ function buildPluginAndApp(feedTemplate, feedTemplateTransforms) {
2122
};
2223

2324
const app = createMockKoopApp();
25+
2426
app.get('/dcat', function (req, res, next) {
2527
req.app.locals.feedTemplateTransforms = feedTemplateTransforms;
2628
res.locals.feedTemplate = feedTemplate;
29+
app.use((err, _req, res, _next) => {
30+
res.status(err.status || 500)
31+
res.send({
32+
error: err.message
33+
})
34+
})
2735
next();
2836
}, plugin.serve.bind(plugin));
2937

@@ -61,7 +69,6 @@ describe('Output Plugin', () => {
6169
mockFetchSite = mocked(fetchSite);
6270

6371
mockFetchSite.mockResolvedValue(mockSiteModel);
64-
6572
[plugin, app] = buildPluginAndApp(dcatTemplate, {});
6673
});
6774

@@ -137,6 +144,25 @@ describe('Output Plugin', () => {
137144
// TODO test stream error
138145
});
139146

147+
it('returns error if stream emits an error', async () => {
148+
const mockReadable = new PassThrough();
149+
150+
plugin.model.pullStream.mockResolvedValue(mockReadable);
151+
const mockError = new Error('stream error')
152+
153+
setTimeout(() => {
154+
mockReadable.emit('error', mockError)
155+
}, 200)
156+
await request(app)
157+
.get('/dcat')
158+
.set('host', siteHostName)
159+
.expect('Content-Type', /application\/json/)
160+
.expect(500)
161+
.expect((res) => {
162+
expect(res.body).toEqual({ error: 'stream error' });
163+
});
164+
});
165+
140166
it('returns 400 when searchRequest returns 400', async () => {
141167
[plugin, app] = buildPluginAndApp({}, {});
142168

src/index.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,11 @@ export = class OutputDcatUs11 {
4747
const { stream: dcatStream } = getDataStreamDcatUs11(feedTemplate, feedTemplateTransforms);
4848

4949
const datasetStream = await this.getDatasetStream(req);
50-
datasetStream
51-
.pipe(dcatStream)
52-
.pipe(res);
50+
datasetStream.on('error', (err) => {
51+
if (req.next) {
52+
req.next(err)
53+
}
54+
}).pipe(dcatStream).pipe(res);
5355

5456
} catch (err) {
5557
res.status(err.statusCode).send(this.getErrorResponse(err));

0 commit comments

Comments
 (0)