fix: extend Node.js IncomingHttpHeaders in our Headers type (#346)

This commit extends Node.js IncomingHttpHeaders in our Headers type.
Changes the Headers type to make it more compatible with Node.js TypeScript projects.

Signed-off-by: Lance Ball <lball@redhat.com>
This commit is contained in:
Lance Ball 2020-10-06 15:50:33 -04:00 committed by GitHub
parent 14468980f7
commit f6be285b83
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 26 additions and 5 deletions

View File

@ -48,6 +48,6 @@ const CONSTANTS = Object.freeze({
DATA_SCHEMA: "dataschema",
DATA_BASE64: "data_base64",
},
});
} as const);
export default CONSTANTS;

View File

@ -1,3 +1,4 @@
import { IncomingHttpHeaders } from "http";
import { CloudEvent } from "..";
import { binary, deserialize, structured, isEvent } from "./http";
import { headersFor } from "./http/headers";
@ -18,8 +19,8 @@ export interface Binding {
* Headers is an interface representing transport-agnostic headers as
* key/value string pairs
*/
export interface Headers {
[key: string]: string;
export interface Headers extends IncomingHttpHeaders {
[key: string]: string | string[] | undefined;
}
/**

View File

@ -2,7 +2,7 @@ import CONSTANTS from "./constants";
import { isString, isDefinedOrThrow, isStringOrObjectOrThrow, ValidationError } from "./event/validation";
export abstract class Parser {
abstract parse(payload: Record<string, unknown> | string): unknown;
abstract parse(payload: Record<string, unknown> | string | string[] | undefined): unknown;
}
export class JSONParser implements Parser {

View File

@ -48,7 +48,7 @@ function superagentEmitter(message: Message, options?: Options): Promise<unknown
}
// set headers
for (const key of Object.getOwnPropertyNames(message.headers)) {
post.set(key, message.headers[key]);
post.set(key, message.headers[key] as string);
}
return post.send(message.body as string);
}

View File

@ -2,6 +2,7 @@ import path from "path";
import fs from "fs";
import { expect } from "chai";
import { IncomingHttpHeaders } from "http";
import { CloudEvent, CONSTANTS, Version } from "../../src";
import { asBase64 } from "../../src/event/validation";
import { Message, HTTP } from "../../src/message";
@ -93,6 +94,25 @@ describe("HTTP transport", () => {
}).to.throw;
});
it("Can be created with Node's IncomingHttpHeaders", () => {
const headers: IncomingHttpHeaders = {
"content-type": CONSTANTS.DEFAULT_CE_CONTENT_TYPE,
};
const body = JSON.stringify({
id,
type,
source,
specversion: Version.V1,
data: { lunch: "tacos" },
});
const message: Message = {
headers,
body,
};
const event = HTTP.toEvent(message);
expect(event.data).to.deep.equal({ lunch: "tacos" });
});
describe("Specification version V1", () => {
const fixture: CloudEvent = new CloudEvent({
specversion: Version.V1,