Last active
July 10, 2024 17:20
-
-
Save joshnuss/fd1d8d3d181fa8ac616ca60c2d692ccb to your computer and use it in GitHub Desktop.
Vite SQL plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'node:fs/promises' | |
export function sql(url) { | |
return { | |
name: 'vite-plugin-sql', | |
// expose an import called 'sql:runtime' | |
resolveId(id) { | |
if (id.startsWith('sql:runtime')) { | |
return id | |
} | |
}, | |
async load(id) { | |
// if requesting to load shared runtime | |
if (id == 'sql:runtime') { | |
// return some code for working with a shared pg.Pool | |
return ` | |
import pg from 'pg' | |
export const pool = new pg.Pool({ connectionString: '${url}' }) | |
` | |
} | |
// otherwise asking to load an .sql file | |
if (!id.endsWith('.sql')) return | |
// read the .sql file | |
const sql = await fs.readFile(id, 'utf8') | |
// represent the .sql as an async JS function | |
return ` | |
import { pool } from 'sql:runtime' | |
export default async function(...values) { | |
const result = await pool.query(\`${sql}\`, values) | |
return result.rows | |
} | |
` | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { sveltekit } from '@sveltejs/kit/vite' | |
import { defineConfig } from 'vite' | |
import { sql } from './vite-plugin-sql' | |
export default defineConfig({ | |
plugins: [ | |
sql('postgres://postgres:postgres@localhost/ecom_dev'), | |
sveltekit() | |
] | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment