Skip to content

Commit

Permalink
refactor: clean up supabase storage key logic
Browse files Browse the repository at this point in the history
  • Loading branch information
0x4007 committed Mar 8, 2024
1 parent 5aa93f1 commit f8201f6
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 79 deletions.
45 changes: 39 additions & 6 deletions build/esbuild-build.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import * as dotenv from "dotenv";
import { config } from "dotenv";
import esbuild from "esbuild";
import { invertColors } from "./plugins/invert-colors";
import { pwaManifest } from "./plugins/pwa-manifest";
import { execSync } from "child_process";
config();

const typescriptEntries = ["src/home/home.ts", "src/progressive-web-app.ts"];
const cssEntries = ["static/style/style.css"];
const entries = [...typescriptEntries, ...cssEntries, "static/manifest.json", "static/favicon.svg", "static/icon-512x512.png"];

export const esBuildContext: esbuild.BuildOptions = {
define: createEnvDefines(["SUPABASE_URL", "SUPABASE_ANON_KEY"]),
plugins: [invertColors, pwaManifest],
sourcemap: true,
entryPoints: entries,
Expand All @@ -23,23 +25,54 @@ export const esBuildContext: esbuild.BuildOptions = {
".json": "file",
},
outdir: "static/dist",
define: createEnvDefines(["SUPABASE_URL", "SUPABASE_ANON_KEY"], {
SUPABASE_STORAGE_KEY: generateSupabaseStorageKey(),
commitHash: execSync(`git rev-parse --short HEAD`).toString().trim(),
}),
};

esbuild
.build(esBuildContext)
.then(() => console.log("\tesbuild complete"))
.catch(console.error);

function createEnvDefines(variableNames: string[]): Record<string, string> {
function createEnvDefines(environmentVariables: string[], generatedAtBuild: Record<string, unknown>): Record<string, string> {
const defines: Record<string, string> = {};
dotenv.config();
for (const name of variableNames) {
for (const name of environmentVariables) {
const envVar = process.env[name];
if (envVar !== undefined) {
defines[`process.env.${name}`] = JSON.stringify(envVar);
defines[name] = JSON.stringify(envVar);
} else {
throw new Error(`Missing environment variable: ${name}`);
}
}
for (const key in generatedAtBuild) {
if (Object.prototype.hasOwnProperty.call(generatedAtBuild, key)) {
defines[key] = JSON.stringify(generatedAtBuild[key]);
}
}
return defines;
}

export function generateSupabaseStorageKey(): string | null {
const SUPABASE_URL = process.env.SUPABASE_URL;
if (!SUPABASE_URL) {
console.error("SUPABASE_URL environment variable is not set");
return null;
}

const urlParts = SUPABASE_URL.split(".");
if (urlParts.length === 0) {
console.error("Invalid SUPABASE_URL environment variable");
return null;
}

const domain = urlParts[0];
const lastSlashIndex = domain.lastIndexOf("/");
if (lastSlashIndex === -1) {
console.error("Invalid SUPABASE_URL format");
return null;
}

return domain.substring(lastSlashIndex + 1);
}
4 changes: 2 additions & 2 deletions cypress/e2e/devpool.cy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RestEndpointMethodTypes } from "@octokit/rest";
import { OAuthToken } from "../../src/home/getters/get-github-access-token";
import { SUPABASE_STORAGE_KEY } from "../../src/home/github-types";
import { generateSupabaseStorageKey } from "../../build/esbuild-build";

describe("DevPool", () => {
let issue1: RestEndpointMethodTypes["issues"]["get"]["response"]["data"];
Expand Down Expand Up @@ -140,7 +140,7 @@ describe("DevPool", () => {
statusCode: 200,
});
// Simulate login token
window.localStorage.setItem(`sb-${SUPABASE_STORAGE_KEY}-auth-token`, JSON.stringify(loginToken));
window.localStorage.setItem(`sb-${generateSupabaseStorageKey()}-auth-token`, JSON.stringify(loginToken));
}).as("githubLogin");
cy.visit("/");
cy.get("#github-login-button").click();
Expand Down
2 changes: 1 addition & 1 deletion src/home/getters/get-github-access-token.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SUPABASE_STORAGE_KEY } from "../github-types";
declare const SUPABASE_STORAGE_KEY: string; // @DEV: passed in at build time check build/esbuild-build.ts
import { checkSupabaseSession } from "../rendering/render-github-login-button";
import { getLocalStore } from "./get-local-store";

Expand Down
3 changes: 2 additions & 1 deletion src/home/getters/get-github-user.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Octokit } from "@octokit/rest";
import { GitHubUser, GitHubUserResponse, SUPABASE_STORAGE_KEY } from "../github-types";
import { GitHubUser, GitHubUserResponse } from "../github-types";
import { OAuthToken } from "./get-github-access-token";
import { getLocalStore } from "./get-local-store";
declare const SUPABASE_STORAGE_KEY: string; // @DEV: passed in at build time check build/esbuild-build.ts

export async function getGitHubUser(): Promise<GitHubUser | null> {
const activeSessionToken = await getSessionToken();
Expand Down
69 changes: 5 additions & 64 deletions src/home/github-types.ts
Original file line number Diff line number Diff line change
@@ -1,77 +1,18 @@
import { TaskNoState } from "./fetch-github/preview-to-full-mapping";
import { RestEndpointMethodTypes } from "@octokit/plugin-rest-endpoint-methods";
export interface GitHubUser {
avatar_url: string;
bio: string;
blog: string;
company: string;
created_at: string;
email: string | null;
events_url: string;
followers_url: string;
followers: number;
following_url: string;
following: number;
gists_url: string;
gravatar_id: string;
hireable: boolean | null;
html_url: string;
id: number;
location: string;
login: string;
name: string;
node_id: string;
organizations_url: string;
public_gists: number;
public_repos: number;
received_events_url: string;
repos_url: string;
site_admin: boolean;
starred_url: string;
subscriptions_url: string;
twitter_username: string;
type: string;
updated_at: string;
url: string;
}
export interface GitHubUserResponse {
status: number;
url: string;
headers: {
"cache-control": string;
"content-type": string;
etag: string;
"last-modified": string;
"x-accepted-oauth-scopes": string;
"x-github-media-type": string;
"x-github-request-id": string;
"x-oauth-scopes": string;
"x-ratelimit-limit": string;
"x-ratelimit-remaining": string;
"x-ratelimit-reset": string;
"x-ratelimit-resource": string;
"x-ratelimit-used": string;
};
data: GitHubUser;
}

export type GitHubIssue = RestEndpointMethodTypes["issues"]["get"]["response"]["data"];
import { TaskNoState } from "./fetch-github/preview-to-full-mapping";

export interface AvatarCache {
[organization: string]: string | null;
}

export const GITHUB_TASKS_STORAGE_KEY = "gitHubTasks";

// supabase key should be dynamic incase of change and testing
let supabaseUrl = "";
if (process.env.SUPABASE_URL) {
supabaseUrl = process.env.SUPABASE_URL.split(".")[0];
}
export const SUPABASE_STORAGE_KEY = supabaseUrl.substring(supabaseUrl.lastIndexOf("/") + 1);

export type TaskStorageItems = {
timestamp: number;
tasks: TaskNoState[];
loggedIn: boolean;
};

export type GitHubUserResponse = RestEndpointMethodTypes["users"]["getByUsername"]["response"];
export type GitHubUser = GitHubUserResponse["data"];
export type GitHubIssue = RestEndpointMethodTypes["issues"]["get"]["response"]["data"];
8 changes: 3 additions & 5 deletions src/home/rendering/render-github-login-button.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { createClient } from "@supabase/supabase-js";
import { toolbar } from "../ready-toolbar";

const supabaseUrl = process.env.SUPABASE_URL;
if (!supabaseUrl) throw new Error("SUPABASE_URL not found");
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY;
if (!supabaseAnonKey) throw new Error("SUPABASE_ANON_KEY not found");
declare const SUPABASE_URL: string; // @DEV: passed in at build time check build/esbuild-build.ts
declare const SUPABASE_ANON_KEY: string; // @DEV: passed in at build time check build/esbuild-build.ts

const supabase = createClient(supabaseUrl, supabaseAnonKey);
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

export function getSupabase() {
return supabase;
Expand Down

0 comments on commit f8201f6

Please sign in to comment.