Skip to content

Instantly share code, notes, and snippets.

@robksawyer
Created May 31, 2024 14:04
Show Gist options
  • Save robksawyer/3a345bdce7dd8ae971945d82355eaae8 to your computer and use it in GitHub Desktop.
Save robksawyer/3a345bdce7dd8ae971945d82355eaae8 to your computer and use it in GitHub Desktop.
This is a custom session storage that is supposed to work with Supabase and the PostgreSQLSessionStorage module.
import { Session } from "@shopify/shopify-api/dist/auth/session";
import { PostgreSQLSessionStorage } from "@shopify/shopify-app-session-storage-postgresql";
import { createClient } from "@supabase/supabase-js";
// Supabase client setup
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_KEY;
if (!supabaseUrl || !supabaseKey) {
throw new Error("Missing Supabase URL or key");
}
export const supabase = createClient(supabaseUrl, supabaseKey);
// PostgreSQL connection URL from Supabase
const postgresUrl = process.env.POSTGRESQL_URL;
if (!postgresUrl) {
throw new Error("Missing PostgreSQL URL");
}
class CustomSessionStorage extends PostgreSQLSessionStorage {
async storeSession(session: Session): Promise<boolean> {
try {
console.log("Storing session:", session);
if (!(session instanceof Session)) {
throw new Error("Invalid session object");
}
// Convert session to property array
const sessionProperties = session.toPropertyArray(true);
// Store session properties
const newSession = sessionProperties.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {} as Record<string, any>);
await super.storeSession(newSession as any);
console.log("Session stored successfully:", session.id);
return true;
} catch (error) {
console.error("Error storing session:", error);
return false;
}
}
async loadSession(id: string): Promise<Session | undefined> {
try {
console.log("Loading session:", id);
const sessionData = await super.loadSession(id);
if (!sessionData) {
console.error(`Session not found: ${id}`);
return undefined;
}
const session = new Session(
sessionData.id,
sessionData.shop,
sessionData.state,
sessionData.isOnline
);
Object.assign(session, sessionData);
console.log("Session loaded successfully:", session.id);
return session;
} catch (error) {
console.error("Error loading session:", error);
return undefined;
}
}
async deleteSession(id: string): Promise<boolean> {
try {
console.log("Deleting session:", id);
await super.deleteSession(id);
console.log("Session deleted successfully:", id);
return true;
} catch (error) {
console.error("Error deleting session:", error);
return false;
}
}
}
// Initialize custom session storage
export const sessionStorage = new CustomSessionStorage(postgresUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment