https://fixtergeek.com/blog/que-son-generics-en-typescript-2023
Last active
June 1, 2023 21:45
-
-
Save HectorBlisS/e995c69e55d452201c3dc00babc87f59 to your computer and use it in GitHub Desktop.
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
/** | |
* Este tipo es la forma de la respuesta de la función. | |
* Puede tener una de estas dos formas. | |
*/ | |
type Result = | |
| { | |
ok: boolean; | |
access_token: string; | |
} | |
| { ok: boolean; error: Error }; | |
/** | |
* Este tipo es la forma de la respuesta de google | |
* (solo el dato que se usa) | |
*/ | |
type Data = { | |
access_token: string; | |
}; | |
/** | |
* Este tipo es la forma de nuestro objeto de llaves | |
*/ | |
type EnvObject = { | |
GOOGLE_SECRET: string; | |
GOOGLE_CLIENT_ID: string; | |
ENV: "production" | "development"; | |
}; | |
/** | |
* Definimos como genericos a Code que extiende o se espera sea de | |
* tipo string, esta extensión me es necesaria porque | |
* code se usará dentro de new URLSearchParams({code}) | |
* el tipo que esta función espera es string. | |
*/ | |
export const getAccessToken = <Code extends string, Env extends EnvObject>( | |
code: Code, | |
env: Env | |
/** | |
* Devolvemos una promesa con nuestro tipo Result. | |
*/ | |
): Promise<Result> => { | |
if (!env || !env.GOOGLE_SECRET || !env.GOOGLE_CLIENT_ID) | |
throw new Error("missing env object"); | |
const url = | |
"https://oauth2.googleapis.com/token?" + | |
new URLSearchParams({ | |
code, | |
client_secret: env.GOOGLE_SECRET, | |
grant_type: "authorization_code", | |
client_id: env.GOOGLE_CLIENT_ID, | |
redirect_uri: | |
env.ENV === "production" | |
? "www.production.com" | |
: "http://localhost:8787", | |
scope: "https://www.googleapis.com/auth/userinfo.email", | |
}); | |
return ( | |
fetch(url, { | |
method: "post", | |
headers: { "content-type": "application/json" }, | |
}) | |
.then((r) => r.json()) | |
/** | |
* Esta es la devolución positiva, usamos nuestro tipo Data. | |
*/ | |
.then((data) => ({ | |
access_token: (data as Data).access_token, | |
ok: true, | |
})) | |
/** | |
* Esta es la devolución negativa, con la forma que definímos antes. | |
*/ | |
.catch((e) => ({ error: e, ok: false })) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment