Skip to content

Commit 93fe246

Browse files
committed
feat(CredentialsMiddleware): add middleware to add cookies to requests
1 parent 0c36d09 commit 93fe246

3 files changed

Lines changed: 43 additions & 1 deletion

File tree

src/middlewares/FetchMiddleware.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,11 @@ export interface IFetchResponse<T> {
2222
clone: () => IFetchResponse<T>;
2323
}
2424

25+
export type TCredentials = "include" | "omit" | "same-origin";
26+
2527
export interface IFetchRequest {
2628
url?: string;
27-
credentials?: "include" | "omit" | "same-origin";
29+
credentials?: TCredentials;
2830
baseUrl?: string;
2931
method?: string;
3032
queryParameters?: {[key: string]: string};
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import {IFetchRequest} from "./FetchMiddleware";
2+
import {IncludeCredentialsMiddleware} from "./IncludeCredentialsMiddleware";
3+
4+
describe("IncludeCredentialsMiddleware", () => {
5+
it("should be defined", () => {
6+
expect(IncludeCredentialsMiddleware).toBeDefined();
7+
});
8+
describe("process", () => {
9+
it("should be defined", () => {
10+
const middleware = new IncludeCredentialsMiddleware();
11+
expect(middleware.process).toBeDefined();
12+
});
13+
it("should set request.credentials to include", () => {
14+
const middleware = new IncludeCredentialsMiddleware();
15+
const spy = jest.fn((options: IFetchRequest) => {
16+
expect(options.credentials).toBe("include");
17+
});
18+
middleware.process({}, spy);
19+
});
20+
it("should be able to set value of credentials via constructor", () => {
21+
const middleware = new IncludeCredentialsMiddleware("omit");
22+
const spy = jest.fn((options: IFetchRequest) => {
23+
expect(options.credentials).toBe("omit");
24+
});
25+
middleware.process({}, spy);
26+
});
27+
});
28+
});
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import {IMiddleware} from "../Stack";
2+
import {IFetchRequest, IFetchResponse, TCredentials} from "./FetchMiddleware";
3+
4+
export class IncludeCredentialsMiddleware implements IMiddleware<IFetchRequest, Promise<IFetchResponse<any>>> {
5+
constructor(private mode: TCredentials = "include") {}
6+
7+
public process(options: IFetchRequest, next: (nextOptions: IFetchRequest) => Promise<IFetchResponse<any>>)
8+
: Promise<IFetchResponse<any>> {
9+
options.credentials = this.mode;
10+
return next(options);
11+
}
12+
}

0 commit comments

Comments
 (0)