Last active
December 8, 2019 02:17
-
-
Save MatteoGioioso/e359b0fe63146006dd3bef2b144f9a8e to your computer and use it in GitHub Desktop.
Small fetch typescript wrapper with Amplify authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Auth, AuthClass } from "aws-amplify"; | |
export interface IOptions extends RequestInit {} | |
export interface IHttpClient { | |
request(url: string, options: IOptions): Promise<any>; | |
authenticatedRequest(url: string, options: IOptions): Promise<any>; | |
} | |
export class HttpClient implements IHttpClient { | |
private _auth: AuthClass; | |
constructor() { | |
this._auth = Auth; | |
} | |
private async setAuthHeader(options: IOptions): Promise<IOptions> { | |
const currentSession = await this._auth.currentAuthenticatedUser(); | |
const headers = { | |
"Content-Type": "application/json", | |
Authorization: "Bearer " + currentSession.signInUserSession.idToken.jwtToken | |
}; | |
return { ...options, headers }; | |
} | |
async request(url: string, options: IOptions): Promise<any> { | |
const response = await fetch(url, options); | |
if (response.status !== 200 && response.status !== 201) { | |
throw new Error("Something went wrong"); | |
} | |
return await response.json(); | |
} | |
async authenticatedRequest(url: string, options: IOptions): Promise<any> { | |
const optionsWithAuth = await this.setAuthHeader(options); | |
return this.request(url, optionsWithAuth); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment