Branchwell

AI Resource Pro / website / scripts / debug-direct-blog-query.ts

1import { createClient } from '@supabase/supabase-js';
2import { existsSync } from 'fs';
3import * as path from 'path';
4import * as dotenv from 'dotenv';
5
6// Load environment variables from .env.local
7const envLocalPath = path.resolve(process.cwd(), '.env.local');
8if (existsSync(envLocalPath)) {
9 console.log(`Loading environment from: ${envLocalPath}`);
10 dotenv.config({ path: envLocalPath });
11} else {
12 console.log(`No .env.local file found at: ${envLocalPath}`);
13 dotenv.config(); // Try loading from default .env
14}
15
16// Get Supabase credentials from environment variables
17const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || '';
18const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || '';
19const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '';
20
21if (!supabaseUrl || !supabaseServiceKey || !supabaseAnonKey) {
22 console.error('Missing Supabase environment variables');
23 process.exit(1);
24}
25
26// Create a service role client to bypass RLS policies
27const serviceClient = createClient(supabaseUrl, supabaseServiceKey, {
28 auth: {
29 persistSession: false,
30 },
31});
32
33// Create a regular anon client like the API would use
34const regularClient = createClient(supabaseUrl, supabaseAnonKey, {
35 auth: {
36 persistSession: false,
37 },
38});
39
40async function main() {
41 console.log('Debugging Supabase blog queries...');
42
43 // 1. Test service client query - this should always work
44 console.log('\n1. Testing service client (admin access)...');
45 try {
46 console.log('Querying all blog posts with service key...');
47 const { data: allPosts, error: allError } = await serviceClient
48 .from('blog_posts')
49 .select('id, title, slug, published')
50 .order('created_at', { ascending: false });
51
52 if (allError) {
53 console.error('Error querying all posts:', allError);
54 } else {
55 console.log(`Found ${allPosts.length} total blog posts with service key`);
56 console.log('Sample posts:');
57 allPosts.slice(0, 3).forEach((post, i) => {
58 console.log(`${i+1}. ${post.title} (${post.slug}) - Published: ${post.published}`);
59 });
60 }
61
62 // Check published posts with service key
63 console.log('\nQuerying published blog posts with service key...');
64 const { data: publishedPosts, error: pubError } = await serviceClient
65 .from('blog_posts')
66 .select('id, title, slug, published')
67 .eq('published', true)
68 .order('created_at', { ascending: false });
69
70 if (pubError) {
71 console.error('Error querying published posts:', pubError);
72 } else {
73 console.log(`Found ${publishedPosts.length} published blog posts with service key`);
74 console.log('Published posts:');
75 publishedPosts.forEach((post, i) => {
76 console.log(`${i+1}. ${post.title} (${post.slug})`);
77 });
78 }
79 } catch (error) {
80 console.error('Error with service client:', error);
81 }
82
83 // 2. Test regular client query - this might be affected by RLS
84 console.log('\n2. Testing regular client (user access like API would use)...');
85 try {
86 console.log('Querying blog posts with anon key...');
87 const { data: regularPosts, error: regularError } = await regularClient
88 .from('blog_posts')
89 .select('id, title, slug, published')
90 .order('created_at', { ascending: false });
91
92 if (regularError) {
93 console.error('Error querying with regular client:', regularError);
94 } else {
95 console.log(`Found ${regularPosts.length} total blog posts with anon key`);
96 console.log('Sample posts:');
97 regularPosts.slice(0, 3).forEach((post, i) => {
98 console.log(`${i+1}. ${post.title} (${post.slug}) - Published: ${post.published}`);
99 });
100 }
101
102 // Check published posts with regular key
103 console.log('\nQuerying published blog posts with anon key...');
104 const { data: regularPublished, error: regPubError } = await regularClient
105 .from('blog_posts')
106 .select('id, title, slug, published')
107 .eq('published', true)
108 .order('created_at', { ascending: false });
109
110 if (regPubError) {
111 console.error('Error querying published posts with anon key:', regPubError);
112 } else {
113 console.log(`Found ${regularPublished.length} published blog posts with anon key`);
114 console.log('Published posts:');
115 regularPublished.forEach((post, i) => {
116 console.log(`${i+1}. ${post.title} (${post.slug})`);
117 });
118 }
119 } catch (error) {
120 console.error('Error with regular client:', error);
121 }
122
123 // 3. Check for specific post (hello-world)
124 console.log('\n3. Checking for specific blog post...');
125 try {
126 // With service key
127 const { data: helloPostAdmin, error: helloErrorAdmin } = await serviceClient
128 .from('blog_posts')
129 .select('id, title, slug, published, content')
130 .eq('slug', 'hello-world')
131 .single();
132
133 if (helloErrorAdmin) {
134 console.error('Error fetching hello-world with service key:', helloErrorAdmin);
135 } else {
136 console.log('Found hello-world post with service key:', {
137 title: helloPostAdmin.title,
138 published: helloPostAdmin.published,
139 contentLength: helloPostAdmin.content.length
140 });
141 }
142
143 // With anon key
144 const { data: helloPostAnon, error: helloErrorAnon } = await regularClient
145 .from('blog_posts')
146 .select('id, title, slug, published')
147 .eq('slug', 'hello-world')
148 .single();
149
150 if (helloErrorAnon) {
151 console.error('Error fetching hello-world with anon key:', helloErrorAnon);
152 } else {
153 console.log('Found hello-world post with anon key:', {
154 title: helloPostAnon.title,
155 published: helloPostAnon.published
156 });
157 }
158 } catch (error) {
159 console.error('Error checking hello-world post:', error);
160 }
161
162 console.log('\nAnalysis:');
163 console.log('- If service client returns posts but regular client does not: Row Level Security (RLS) issue');
164 console.log('- If both clients return posts but API doesn\'t: API implementation issue');
165 console.log('- If neither client returns posts: Database connection or schema issue');
166}
167
168main();