Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add global headers to the client #218

Merged
merged 7 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions src/client/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { nanoid } from "nanoid";
import { Client } from "./client";
import type { PublishToUrlResponse } from "../../dist";

export const clearQueues = async (client: Client) => {
const queueDetails = await client.queue().list();
Expand Down Expand Up @@ -100,6 +101,163 @@ describe("E2E Publish", () => {
expect(verifiedMessage.maxRetries).toBeGreaterThanOrEqual(retryCount);
expect(verifiedMessage.failureCallback).toBe("https://oz.requestcatcher.com/?foo=bar");
});

test("should use global headers", async () => {
const clientWithHeaders = new Client({
token: process.env.QSTASH_TOKEN!,
// @ts-expect-error undefined header
headers: {
"undefined-header": undefined,
"test-header": "value",
"test-header-2": "value-2",
"TEST-CASE": "value-uppercase",
"test-case": "value-lowercase",
},
});
const result = await clientWithHeaders.publish({
url: "https://example.com/",
});

const verifiedMessage = await client.messages.get(result.messageId);
const messageHeaders = new Headers(verifiedMessage.header);

expect(messageHeaders.get("test-header")).toEqual("value");
expect(messageHeaders.get("test-header-2")).toEqual("value-2");
expect(messageHeaders.get("test-case")).toEqual("value-uppercase, value-lowercase");
expect(messageHeaders.get("undefined-header")).toEqual("undefined");
});

test("should override global headers", async () => {
const clientWithHeaders = new Client({
token: process.env.QSTASH_TOKEN!,
headers: {
"test-header": "value",
"test-header-2": "value-2",
"stays-same": "same",
},
});
const result = await clientWithHeaders.publish({
url: "https://example.com/",
headers: {
"Test-Header": "override-value",
},
});

const verifiedMessage = await client.messages.get(result.messageId);
const messageHeaders = new Headers(verifiedMessage.header);

expect(messageHeaders.get("test-header")).toEqual("override-value");
expect(messageHeaders.get("test-header-2")).toEqual("value-2");
expect(messageHeaders.get("stays-same")).toEqual("same");
});

test("should override global headers with publishJSON if headers are provided", async () => {
const clientWithHeaders = new Client({
token: process.env.QSTASH_TOKEN!,
headers: {
"test-header": "value",
"test-header-2": "value-2",
},
});
const result = await clientWithHeaders.publishJSON({
url: "https://example.com/",
headers: {
"Test-Header": "override-value",
"stays-same": "same",
},
});

const verifiedMessage = await client.messages.get(result.messageId);
const messageHeaders = new Headers(verifiedMessage.header);

expect(messageHeaders.get("test-header")).toEqual("override-value");
expect(messageHeaders.get("test-header-2")).toEqual("value-2");
expect(messageHeaders.get("stays-same")).toEqual("same");
});
});

describe("E2E Batch", () => {
test("should override global headers", async () => {
const client = new Client({
token: process.env.QSTASH_TOKEN!,
headers: {
"test-header": "value",
"test-header-2": "value-2",
},
});
const result = (await client.batch([
{
url: "https://example.com/1",
headers: {
"Test-Header": "override-value-1",
"stays-same": "same",
},
},
{
url: "https://example.com/2",
headers: {
"Test-Header": "override-value-2",
"stays-same": "same",
},
},
])) as PublishToUrlResponse[];

const verifiedMessage1 = await client.messages.get(result[0].messageId);
const messageHeaders1 = new Headers(verifiedMessage1.header);

const verifiedMessage2 = await client.messages.get(result[1].messageId);
const messageHeaders2 = new Headers(verifiedMessage2.header);

expect(messageHeaders1.get("test-header")).toEqual("override-value-1");
expect(messageHeaders2.get("test-header")).toEqual("override-value-2");

expect(messageHeaders1.get("stays-same")).toEqual("same");
expect(messageHeaders2.get("stays-same")).toEqual("same");

expect(messageHeaders1.get("test-header-2")).toEqual("value-2");
expect(messageHeaders2.get("test-header-2")).toEqual("value-2");
});

test("should override global headers with batchJSON", async () => {
const client = new Client({
token: process.env.QSTASH_TOKEN!,
headers: {
"test-header": "value",
"test-header-2": "value-2",
},
});
const result = (await client.batchJSON([
{
url: "https://example.com/1",
headers: {
"Test-Header": "override-value-1",
"stays-same": "same",
},
},
{
url: "https://example.com/2",
headers: {
"Test-Header": "override-value-2",
"stays-same": "same",
},
},
])) as PublishToUrlResponse[];

const verifiedMessage1 = await client.messages.get(result[0].messageId);
const messageHeaders1 = new Headers(verifiedMessage1.header);

const verifiedMessage2 = await client.messages.get(result[1].messageId);
const messageHeaders2 = new Headers(verifiedMessage2.header);

expect(messageHeaders1.get("test-header")).toEqual("override-value-1");
expect(messageHeaders2.get("test-header")).toEqual("override-value-2");

expect(messageHeaders1.get("stays-same")).toEqual("same");
expect(messageHeaders2.get("stays-same")).toEqual("same");

expect(messageHeaders1.get("test-header-2")).toEqual("value-2");
expect(messageHeaders2.get("test-header-2")).toEqual("value-2");
});
});

describe("E2E Url Group Publish", () => {
Expand Down
24 changes: 22 additions & 2 deletions src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ type ClientConfig = {
* Configure how the client should retry requests.
*/
retry?: RetryConfig;

/**
* Global headers to send with each request.
* These can be overridden by the headers in the request.
*/
headers?: HeadersInit;
};

export type PublishBatchRequest<TBody = BodyInit> = PublishRequest<TBody> & {
Expand Down Expand Up @@ -265,6 +271,7 @@ export type QueueRequest = {
export class Client {
public http: Requester;
private token: string;
private headers: Headers;

public constructor(config: ClientConfig) {
this.http = new HttpClient({
Expand All @@ -273,6 +280,19 @@ export class Client {
authorization: `Bearer ${config.token}`,
});
this.token = config.token;
//@ts-expect-error caused by undici and bunjs type overlap
this.headers = prefixHeaders(new Headers(config.headers));
}

private wrapWithGlobalHeaders(headers: Headers) {
const finalHeaders = new Headers(this.headers);

// eslint-disable-next-line unicorn/no-array-for-each
headers.forEach((value, key) => {
finalHeaders.set(key, value);
});

return finalHeaders;
}
Copy link
Collaborator

@fahreddinozcan fahreddinozcan Dec 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private wrapWithGlobalHeaders(headers: Headers) {
const finalHeaders = new Headers(this.headers);
// eslint-disable-next-line unicorn/no-array-for-each
headers.forEach((value, key) => {
finalHeaders.set(key, value);
});
return finalHeaders;
}
private wrapWithGlobalHeaders(headers: Headers) {
const finalHeaders = new Headers(this.headers);
// eslint-disable-next-line unicorn/no-array-for-each
headers.forEach((key, value) => {
finalHeaders.set(key, value);
});
return finalHeaders;
}

Why do we even have this function? Are we trying to reverse the headers' key value? The user should already give them as

    const clientWithHeaders = new Client({
      token: process.env.QSTASH_TOKEN!,
      headers: {
        "test-header": "value",
        "test-header-2": "value-2",
      },
    });

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is reversed in the api for no reason. It seemed weird to me too


/**
Expand Down Expand Up @@ -357,7 +377,7 @@ export class Client {
public async publish<TRequest extends PublishRequest>(
request: TRequest
): Promise<PublishResponse<TRequest>> {
const headers = processHeaders(request);
const headers = this.wrapWithGlobalHeaders(processHeaders(request)) as HeadersInit;
const response = await this.http.request<PublishResponse<TRequest>>({
path: ["v2", "publish", getRequestPath(request)],
body: request.body,
Expand Down Expand Up @@ -399,7 +419,7 @@ export class Client {
public async batch(request: PublishBatchRequest[]): Promise<PublishResponse<PublishRequest>[]> {
const messages = [];
for (const message of request) {
const headers = processHeaders(message);
const headers = this.wrapWithGlobalHeaders(processHeaders(message));
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore Type mismatch TODO: should be checked later
const headerEntries = Object.fromEntries(headers.entries());
Expand Down
Loading