Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
zobweyt committed Aug 29, 2024
1 parent 47586c9 commit 65f5591
Show file tree
Hide file tree
Showing 11 changed files with 44 additions and 74 deletions.
2 changes: 1 addition & 1 deletion frontend/src/lib/api/auth/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const authenticate = action(async (form: LoginForm) => {
await updateSession(data);
}
if (error) {
return { error, code: response.status };
return { error, code: response.clone().status };
}

throw redirect(form.redirect || "/");
Expand Down
10 changes: 3 additions & 7 deletions frontend/src/lib/api/auth/service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { getClient } from "../client";
import { components } from "../schema";
import { formDataSerializer } from "../serializers";
import client from "~/lib/api/client";
import { components } from "~/lib/api/schema";
import { formDataSerializer } from "~/lib/api/serializers";

export const $authenticate = async (username: string, password: string) => {
"use server";

const client = await getClient();

return await client.POST("/api/v1/auth/login", {
body: {
scope: "auth",
Expand All @@ -20,8 +18,6 @@ export const $authenticate = async (username: string, password: string) => {
export const $resetPassword = async (body: components["schemas"]["UserPasswordReset"]) => {
"use server";

const client = await getClient();

return await client.PATCH("/api/v1/auth/reset-password", {
body: body,
});
Expand Down
17 changes: 7 additions & 10 deletions frontend/src/lib/api/client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import createClient from "openapi-fetch";

import { AUTH_MIDDLEWARE, DEBUG_MIDDLEWARE } from "~/lib/api/middleware";
import type { paths } from "~/lib/api/schema";

export const getClient = async () => {
"use server";

const client = createClient<paths>({ baseUrl: import.meta.env.VITE_API_URL });
const client = createClient<paths>({ baseUrl: import.meta.env.VITE_API_URL });

client.use(AUTH_MIDDLEWARE);
client.use(AUTH_MIDDLEWARE);

if (import.meta.env.DEV) {
client.use(DEBUG_MIDDLEWARE);
}
if (import.meta.env.DEV) {
client.use(DEBUG_MIDDLEWARE);
}

return client;
};
export default client;
11 changes: 6 additions & 5 deletions frontend/src/lib/api/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import logger from "~/lib/logging/console";
export const AUTH_MIDDLEWARE: Middleware = {
onRequest: async ({ request }) => {
const session = await getSession();
const auth = session.data.jwt;
const jwt = session.data.jwt;

if (auth && Date.parse(auth.expires_at) > Date.now()) {
request.headers.set("Authorization", `${auth.token_type} ${auth.access_token}`);
if (jwt && Date.parse(jwt.expires_at) > Date.now()) {
request.headers.set("Authorization", `${jwt.token_type} ${jwt.access_token}`);
}

return request;
Expand All @@ -23,8 +23,9 @@ export const DEBUG_MIDDLEWARE: Middleware = {
const method = colors.white(request.method);
const route = colors.cyan(colors.underline(request.url));

const colorizeStatus = response.status >= 400 && response.status < 600 ? colors.red : colors.green;
const status = colorizeStatus(`${response.status} ${response.statusText}`);
const clone = response.clone();
const colorizeStatus = clone.status >= 400 && clone.status < 600 ? colors.red : colors.green;
const status = colorizeStatus(`${clone.status} ${clone.statusText}`);

const icon = request.headers.has("Authorization") ? "🔓" : "🔒";

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lib/api/otp/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ export const $isCorrectOtp = cache(async (body: components["schemas"]["CodeVerif

const { response } = await $verifyOtp(body);

return response.status === 202;
return response.clone().status === 202;
}, "$isCorrectOtp");
6 changes: 1 addition & 5 deletions frontend/src/lib/api/otp/service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { getClient } from "../client";
import client from "~/lib/api/client";
import { components } from "../schema";

export const $sendOtp = async (email: string) => {
"use server";

const client = await getClient();

return await client.POST("/api/v1/verification/request", {
body: {
email: email,
Expand All @@ -16,8 +14,6 @@ export const $sendOtp = async (email: string) => {
export const $verifyOtp = async (body: components["schemas"]["CodeVerify"]) => {
"use server";

const client = await getClient();

return await client.POST("/api/v1/verification/verify", {
body: body,
});
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lib/api/users/me/actions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { action } from "@solidjs/router";
import { $removeCurrentUserAvatar, $updateCurrentUserAvatar } from "./service";

// import { me } from ".";
import { $removeCurrentUserAvatar, $updateCurrentUserAvatar } from "./service";

export const removeCurrentUserAvatar = action(async () => {
"use server";
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/lib/api/users/me/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getCurrentUser } from "./service";
export const $getCurrentUser = cache(async () => {
"use server";

const result = await getCurrentUser();
const { data } = await getCurrentUser();

return result.data;
return data;
}, "$getCurrentUser");
12 changes: 2 additions & 10 deletions frontend/src/lib/api/users/me/service.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
// import { formDataSerializer, getClient } from "~/lib/api";

import { getClient } from "../../client";
import { formDataSerializer } from "../../serializers";
import client from "~/lib/api/client";
import { formDataSerializer } from "~/lib/api/serializers";

export const getCurrentUser = async () => {
"use server";

const client = await getClient();

return await client.GET("/api/v1/users/me");
};

export const $removeCurrentUserAvatar = async () => {
"use server";

const client = await getClient();

return await client.DELETE("/api/v1/users/me/avatar");
};

export const $updateCurrentUserAvatar = async (file: File) => {
"use server";

const client = await getClient();

return await client.PATCH("/api/v1/users/me/avatar", {
body: {
file: file,
Expand Down
4 changes: 1 addition & 3 deletions frontend/src/lib/api/users/service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { getClient } from "../client";
import client from "~/lib/api/client";

export const exists = async (email: string) => {
"use server";

const client = await getClient();

return await client.POST("/api/v1/users/exists", {
body: {
email: email,
Expand Down
47 changes: 19 additions & 28 deletions frontend/src/lib/logging/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,34 @@ import colors from "picocolors";
import Logger from "./logger";
import { LogLevel, type LogEvent } from "./types";

export class ConsoleLogger extends Logger {
protected static _instance: ConsoleLogger = new this();

protected static dispatchers: Record<LogLevel, (message: any) => void> = {
dbug: console.debug,
info: console.info,
warn: console.warn,
crit: console.error,
};

protected static styles: Record<LogLevel, (message: any) => string> = {
dbug: colors.gray,
info: colors.green,
warn: colors.yellow,
crit: colors.red,
};

protected constructor() {
super();
}
export const DISPATCHERS: Record<LogLevel, (args: any[]) => void> = {
dbug: console.debug,
info: console.info,
warn: console.warn,
crit: console.error,
};

export const STYLES: Record<LogLevel, (message: any) => string> = {
dbug: colors.gray,
info: colors.green,
warn: colors.yellow,
crit: colors.red,
};

export class ConsoleLogger extends Logger {
protected override write(event: LogEvent): void {
const message = this.format(event);
ConsoleLogger.dispatchers[event.level](message);
DISPATCHERS[event.level](message);
}

protected format(event: LogEvent): any {
const timestamp = colors.dim(new Date().toLocaleTimeString());
const severity = colors.bold(ConsoleLogger.styles[event.level](`[${event.level}]`));
return `${timestamp} ${severity} ${event.args.join(" ")}`;
}

public static get instance(): ConsoleLogger {
return this._instance;
const severity = colors.bold(STYLES[event.level](`[${event.level}]`));
const args = event.args.join(" ");
return `${timestamp} ${severity} ${args}`;
}
}

export const logger = ConsoleLogger.instance;
export const logger = new ConsoleLogger();

export default logger;

0 comments on commit 65f5591

Please sign in to comment.