Skip to content

Commit

Permalink
Merge pull request #1 from OttlikG/add-attributes-to-header
Browse files Browse the repository at this point in the history
Add attributes to header
  • Loading branch information
manterfield authored Oct 27, 2022
2 parents c234639 + df9ced3 commit dd989c6
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
10 changes: 9 additions & 1 deletion nestjs-pubsub-interceptor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export class MessageDecodingInterceptor implements NestInterceptor {
}
}

private addAttributesToHeader(attributes: any, request: Request) {
Object.keys(attributes).forEach((key) => {
request.headers[`x-pubsub-${key}`] = attributes[key]
})
}

async intercept(
context: ExecutionContext,
next: CallHandler,
Expand All @@ -40,7 +46,9 @@ export class MessageDecodingInterceptor implements NestInterceptor {

try {
// Now allow handlers to focus on the unwrapped/decoded body
request.body = await this.parseMessagePayload(request.body.message);
const message = await this.parseMessagePayload(request.body.message);
this.addAttributesToHeader(request.body.message.attributes, request);
request.body = message;
return next.handle();
} catch (e) {
// We re-raise any non-validation errors as these are unhandled
Expand Down
8 changes: 8 additions & 0 deletions test-app/src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
UseInterceptors,
UsePipes,
ValidationPipe,
Headers,
} from '@nestjs/common';
import { AppService } from './app.service';
import { MessageDecodingInterceptor } from '@hiphops/nestjs-pubsub-interceptor';
Expand All @@ -27,4 +28,11 @@ export class AppController {
root(@Body() someObject: SomeDto): string {
return someObject.someString;
}

@Post('headers')
@UseInterceptors(MessageDecodingInterceptor)
@UsePipes(new ValidationPipe({ transform: true }))
headers(@Headers() headers): string {
return headers;
}
}
19 changes: 19 additions & 0 deletions test-app/test/app.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,23 @@ describe('AppController (e2e)', () => {

return request(app.getHttpServer()).post('/').send(msgPayload).expect(400);
});

it('/task-request (POST) should return 201 with no attributes', () => {
msgPayload.message.attributes = {};
return request(app.getHttpServer())
.post('/headers')
.send(msgPayload)
.expect(201);
});

it('/task-request (POST) should add header based on attributes', (done) => {
request(app.getHttpServer())
.post('/headers')
.send(msgPayload)
.expect(201)
.end(function (err, res) {
expect(res.body['x-pubsub-foo']).toBe('bar');
done();
});
});
});

0 comments on commit dd989c6

Please sign in to comment.