feat: integrate tRPC client with Clerk authentication
- Update trpc-client.ts with auth token management - Create comprehensive tRPC hooks for all project operations - Store Clerk session token in localStorage for API auth - Clear token on sign out - Support integer IDs matching backend schema Hooks created: - Projects: useProjects, useProject, useCreateProject, useUpdateProject, useDeleteProject - Characters: useCharacters, useCharacter, useCreateCharacter, useUpdateCharacter, useDeleteCharacter - Relationships: useRelationships, useCharacterRelationships, useCreateRelationship, useUpdateRelationship, useDeleteRelationship - Scenes: useScenes, useScene, useCreateScene, useUpdateScene, useDeleteScene - Stats: useCharacterStats, useProjectCharacterStats All 34 backend tests passing.
This commit is contained in:
@@ -1,31 +1,39 @@
|
||||
import { createTRPCClient, httpBatchLink } from '@trpc/client';
|
||||
import type { AppRouter } from '../../../server/trpc';
|
||||
|
||||
// Create tRPC client
|
||||
export function createTRPCClientInstance(baseUrl: string = 'http://localhost:8080') {
|
||||
return createTRPCClient<AppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: `${baseUrl}/trpc`,
|
||||
headers: () => {
|
||||
// Add auth headers if available
|
||||
const token = localStorage.getItem('auth_token');
|
||||
return {
|
||||
authorization: token ? `Bearer ${token}` : '',
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
let cachedToken: string | null = null;
|
||||
|
||||
function getAuthToken(): string | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
if (cachedToken) return cachedToken;
|
||||
cachedToken = localStorage.getItem('auth_token');
|
||||
return cachedToken;
|
||||
}
|
||||
|
||||
// Helper for SSR
|
||||
export function createServerTRPCClient(baseUrl: string = 'http://localhost:8080') {
|
||||
return createTRPCClient<AppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: `${baseUrl}/trpc`,
|
||||
}),
|
||||
],
|
||||
});
|
||||
export function setAuthToken(token: string | null) {
|
||||
cachedToken = token;
|
||||
if (typeof window !== 'undefined') {
|
||||
if (token) {
|
||||
localStorage.setItem('auth_token', token);
|
||||
} else {
|
||||
localStorage.removeItem('auth_token');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create tRPC client with auth
|
||||
export const trpc = createTRPCClient<AppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: `${(import.meta as any).env?.VITE_API_URL || 'http://localhost:8080'}/trpc`,
|
||||
headers: () => {
|
||||
const token = getAuthToken();
|
||||
return {
|
||||
authorization: token ? `Bearer ${token}` : '',
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
export type { AppRouter };
|
||||
|
||||
Reference in New Issue
Block a user