Skip to content

Commit

Permalink
feat: setup client and dicorc libraries
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed May 27, 2021
1 parent 85b2da0 commit 5456dd0
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/core/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import _fetch from "node-fetch";
import { API_ENDPOINT } from "../lib";
import { Config } from "./dicorc";

export const fetch = async <R>(
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<Required<Config>["user"]> => {
const {
data: { fullname, email }
} = await fetch<Required<Config>["user"]>("/whoami", token);

return {
token,
fullname,
email
};
};
84 changes: 84 additions & 0 deletions src/core/dicorc.ts
Original file line number Diff line number Diff line change
@@ -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<Required<Config>["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<boolean> => {
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;
};

0 comments on commit 5456dd0

Please sign in to comment.