Skip to content

Instantly share code, notes, and snippets.

@ttlg
Last active November 2, 2024 07:21
Show Gist options
  • Save ttlg/ca7093a8210fa0ecce5abda863fba9ae to your computer and use it in GitHub Desktop.
Save ttlg/ca7093a8210fa0ecce5abda863fba9ae to your computer and use it in GitHub Desktop.
OpenNextJS Cloudflare D1疎通確認
import { getRequestContext } from "@cloudflare/next-on-pages";
export const runtime = "edge";
interface ExtendedCloudflareEnv {
DB: D1Database;
AI?: {
run: (model: string, options: any) => Promise<any>;
};
}
export const getEnv = (): ExtendedCloudflareEnv => {
const context = getRequestContext();
const env = context.env as ExtendedCloudflareEnv;
return env;
};
export async function GET(request: Request) {
try {
const env = getEnv();
const tablesResult = await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table'").all<{ name: string }>();
const tables = tablesResult.results.map(row => row.name);
const tablesInfo: Record<string, any[]> = {};
for (const table of tables) {
const columnsResult = await env.DB.prepare(`PRAGMA table_info(${table})`).all<{
cid: number;
name: string;
type: string;
notnull: number;
dflt_value: string | null;
pk: number
}>();
tablesInfo[table] = columnsResult.results.map(column => ({
name: column.name,
type: column.type,
}));
}
return new Response(JSON.stringify(tablesInfo, null, 2), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error('DB接続エラー:', error);
return new Response(JSON.stringify({ error: 'Failed to fetch table information' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment