chore(#4): Add a database connection to mongodb

This commit is contained in:
Josh Creek
2024-04-06 15:04:53 +01:00
parent 26c552e994
commit 49e39c2742
7 changed files with 817 additions and 88 deletions
+1
View File
@@ -0,0 +1 @@
MONGO_URL=""
+735 -79
View File
File diff suppressed because it is too large Load Diff
+9 -2
View File
@@ -14,7 +14,7 @@
"devDependencies": {
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/adapter-netlify": "^4.1.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/kit": "^2.0.6",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@types/eslint": "^8.56.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
@@ -30,5 +30,12 @@
"typescript": "^5.0.0",
"vite": "^5.0.3"
},
"type": "module"
"type": "module",
"dependencies": {
"mongoose": "^8.0.3",
"nanoid": "^5.0.4"
},
"engines": {
"node": ">=18.13.0"
}
}
+7 -7
View File
@@ -1,13 +1,13 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};
+9
View File
@@ -0,0 +1,9 @@
import type { Handle } from '@sveltejs/kit';
import { dbConnect } from '$lib/utils/db';
await dbConnect();
export const handle: Handle = async ({ event, resolve }) => {
const response = await resolve(event);
return response;
};
+51
View File
@@ -0,0 +1,51 @@
import mongoose from 'mongoose';
import { getEnv } from '$lib/utils/env';
const env = getEnv();
/*
0 - disconnected
1 - connected
2 - connecting
3 - disconnecting
4 - uninitialized
*/
let mongoConnectionState = 0;
export const dbConnect = async () => {
if (mongoConnectionState === 1) {
console.log('connection established');
return;
}
if (mongoose.connections.length > 0) {
mongoConnectionState = mongoose.connections[0].readyState;
if (mongoConnectionState === 1) {
console.log('using existing connection');
return;
}
await mongoose.disconnect();
}
try {
await mongoose.connect(env.MONGO_URL, {
serverApi: { version: '1', strict: true, deprecationErrors: true }
});
await mongoose.connection.db.admin().command({ ping: 1 });
console.log('Pinged your deployment. You successfully connected to MongoDB!');
mongoConnectionState = 1;
} finally {
// Ensures that the client will close when you finish/error
await mongoose.disconnect();
}
mongoConnectionState = 1;
};
export const dbDisconnect = async () => {
if (process.env.NODE_ENV === 'development') return;
if (mongoConnectionState === 0) return;
await mongoose.disconnect();
mongoConnectionState = 0;
console.log('disconnected from mongodb');
};
+5
View File
@@ -0,0 +1,5 @@
export function getEnv() {
return {
MONGO_URL: import.meta.env.VITE_MONGO_URL
};
}