Skip to content

Commit

Permalink
Merge pull request #207 from cyberhck/patch-1
Browse files Browse the repository at this point in the history
test(ContentTypeMiddleware): add content-type middleware
  • Loading branch information
paibamboo authored Oct 2, 2020
2 parents a13ba57 + c2de7e8 commit a308d2a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/middlewares/ContentTypeMiddleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {ContentTypeMiddleware} from "./ContentTypeMiddleware";
import {IFetchRequest} from "./FetchMiddleware";

describe("ContentTypeMiddleware", () => {
it("should add a content type application/json by default", () => {
const spy = jest.fn((options: IFetchRequest) => {
const contentType = options.headers && options.headers["content-type"];
expect(contentType).toBe("application/json");
});
const mw = new ContentTypeMiddleware();
mw.process({}, spy);
});
it("should accept a content type in constructor if we want to change it", () => {
const spy = jest.fn((options: IFetchRequest) => {
const contentType = options.headers && options.headers["content-type"];
expect(contentType).toBe("text/plain");
});
const mw = new ContentTypeMiddleware("text/plain");
mw.process({}, spy);
});
});
15 changes: 15 additions & 0 deletions src/middlewares/ContentTypeMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {IMiddleware} from "../Stack";
import {IFetchRequest, IFetchResponse} from "./FetchMiddleware";

export class ContentTypeMiddleware implements IMiddleware<IFetchRequest, Promise<IFetchResponse<any>>> {
constructor(private contentType: string = "application/json") {
}

public process(options: IFetchRequest, next: (nextOptions: IFetchRequest) => Promise<IFetchResponse<any>>): Promise<IFetchResponse<any>> {
if (!options.headers) {
options.headers = {};
}
options.headers["content-type"] = this.contentType;
return next(options);
}
}
1 change: 1 addition & 0 deletions src/middlewares/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export * from "./FetchMiddleware";
export * from "./MockMiddleware";
export * from "./CacheMiddleware";
export * from "./IncludeCredentialsMiddleware";
export * from "./ContentTypeMiddleware";

0 comments on commit a308d2a

Please sign in to comment.