I have been using sqlite3 for most of my fullstack applications (node/express, django/drf + svelte on the front end as the consumer of the api endpoints) and have been trying to figure out how to integrate sqlite3.
Here is what I did
I am assuming you are familiar with sveltekit. For those who are new, you can go check out SvelteKit
database.js file inside src/lib folderimport sqlite from 'better-sqlite3'
const DB = new sqlite('./annadb.sqlite')
const schema = `CREATE TABLE IF NOT EXISTS posts(
id INTEGER NOT NULL PRIMARY KEY,
title TEXT NOT NULL
)`;
DB.exec(schema)
export default DB
index.json.js endpoint to get all articles from the database inside the src/routes folder withe the following code:import DB from '$lib/database.js'
export async function get() {
const articles = await DB.prepare('SELECT * FROM posts').all()
if (articles) {
return {
body: {
articles
}
}
}
}
<script context="module">
export async function load({ fetch }) {
const res = await fetch(/index.json);
if (res.ok) {
return {
props: {
articles: await res.json(),
},
};
}
return {
status: res.status,
error: new Error("Could not load"),
};
}
</script>
<script>
export let articles;
let latestArticles = articles.articles;
console.log(articles);
</script>
<main>
{#if latestArticles.length > 0}
{#each latestArticles as article}
<h2>{article.title}</h2>
{/each}
{:else}
<p>Articles are coming soon</p>
{/if}
</main>
That's it.
As far as I know, better-sqlite3 is a synchronous library.
I notice you're using await with better-sqlite3. Removing await might solve your problem.