diff --git a/src/core/client.ts b/src/core/client.ts new file mode 100644 index 0000000..451fdc1 --- /dev/null +++ b/src/core/client.ts @@ -0,0 +1,48 @@ +import _fetch from "node-fetch"; +import { API_ENDPOINT } from "../lib"; +import { Config } from "./dicorc"; + +export const fetch = async ( + endpoint: string, + token: string, + options?: { [key: string]: unknown } +): Promise<{ status: number; msg: string; data: R }> => { + const headers: { [key: string]: string } = { + authorization: `Bearer ${token}` + }; + + if (options && options.headers && typeof options.headers === "object") { + Object.entries(options.headers).map(([k, v]) => { + if (typeof v === "string") { + headers[k] = v; + } + }); + } + + const response = await _fetch(`${API_ENDPOINT}${endpoint}`, { + ...options, + headers + }); + + const json = await response.json(); + + if (!response.ok) { + throw json || response; + } + + return json; +}; + +export const whoami = async ( + token: string +): Promise["user"]> => { + const { + data: { fullname, email } + } = await fetch["user"]>("/whoami", token); + + return { + token, + fullname, + email + }; +}; diff --git a/src/core/dicorc.ts b/src/core/dicorc.ts new file mode 100644 index 0000000..a79a13e --- /dev/null +++ b/src/core/dicorc.ts @@ -0,0 +1,84 @@ +import * as rc from "rc9"; +import { RC_FILE } from "../lib"; +import * as client from "./client"; + +export interface Config { + user?: { + token: string; + fullname: string; + email: string; + }; +} + +/** + * Read config file + */ +export const read = (): Config => { + return rc.readUser(RC_FILE); +}; + +/** + * Write config file + */ +export const write = (config: Config): void => { + rc.writeUser(config, RC_FILE); +}; + +/** + * Update config file + */ +export const update = (config: Config): void => { + rc.updateUser(config, RC_FILE); +}; + +/** + * Sign in used + */ +export const signin = async ( + token: string +): Promise["user"]> => { + const user = await client.whoami(token); + + update({ user }); + + return user; +}; + +/** + * Sign out user + */ +export const signout = (): void => { + const config = read(); + + delete config.user; + + write(config); +}; + +/** + * Check if user is signed in + */ +export const isSignedIn = async (): Promise => { + const config = read(); + + if (!config.user) { + return false; + } + + // Invalid token + if (config.user.token.length !== 64) { + signout(); + + return false; + } + + try { + await client.whoami(config.user.token); + } catch (error) { + signout(); + + console.log(error); + } + + return true; +};