Skip to content

Commit a56df84

Browse files
Merge pull request #111 from sqlitecloud/improve-examples-js
fix(nodejs): use isConnect()
2 parents bac8f9f + deea640 commit a56df84

File tree

2 files changed

+32
-14
lines changed

2 files changed

+32
-14
lines changed

sqlite-cloud/quick-start-next.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export function DatabaseProvider({ children, config }: DatabaseProviderProps) {
5353
const dbRef = useRef<Database | null>(null);
5454

5555
useEffect(() => {
56-
if (dbRef.current) return; // Connection already exists
56+
if (dbRef.current && dbRef.current.isConnected()) return; // Connection already exists
5757

5858
try {
5959
dbRef.current = new Database(config.connectionString);

sqlite-cloud/quick-start-node.mdx

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,25 +29,43 @@ npm install express @sqlitecloud/drivers --save
2929
- Paste the following into your `index.js` file:
3030

3131
```javascript
32-
const express = require('express');
33-
const { Database } = require('@sqlitecloud/drivers');
32+
const express = require("express");
33+
const { Database } = require("@sqlitecloud/drivers");
3434

3535
const app = express();
36-
const db = new Database('<your-connection-string>');
37-
38-
app.get('/albums', async (req, res) => {
39-
const result = await db.sql`
40-
USE DATABASE chinook.sqlite;
41-
SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist
42-
FROM albums
43-
INNER JOIN artists
44-
WHERE artists.ArtistId = albums.ArtistId
45-
LIMIT 20;`;
36+
let db;
37+
38+
function getDatabase() {
39+
if (!db || !db.isConnected()) {
40+
db = new Database("<connection-string>", (error) => {
41+
if (error) {
42+
console.log("Error during the connection", error);
43+
} else {
44+
console.log("Connected to the database");
45+
}
46+
});
47+
}
48+
49+
return db;
50+
}
51+
52+
app.get("/albums", async (req, res) => {
53+
try {
54+
const result = await getDatabase().sql(`
55+
USE DATABASE chinook.sqlite;
56+
SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist
57+
FROM albums
58+
INNER JOIN artists
59+
WHERE artists.ArtistId = albums.ArtistId
60+
LIMIT 20;`);
4661
res.json(result);
62+
} catch (error) {
63+
res.status(500).json({ error: error.message });
64+
}
4765
});
4866

4967
app.listen(3000, () => {
50-
console.log('Server running on port 3000');
68+
console.log("Server running on port 3000");
5169
});
5270
```
5371
5. **Run your app**

0 commit comments

Comments
 (0)