refactor(server/middleware): move common logic for maintaining a database connection to another file

This commit is contained in:
parent a16e58b2b4
commit cfb1f69ffb
Signed by: tablet
GPG Key ID: 924A5F6AF051E87C
3 changed files with 43 additions and 19 deletions

20
lib/server/plugnplay.ts Normal file

@ -0,0 +1,20 @@
import mongoose from "mongoose";
import { Biffno } from "~/models/challenges/biffno";
import { Ficmas } from "~/models/challenges/ficmas";
import { Challenge } from "~/models/challenges/gen";
export default async function () {
let beep = useRuntimeConfig();
Challenge;
Biffno;
Ficmas;
console.log(mongoose.connection.modelNames);
console.log(beep);
try {
await mongoose.connect(beep.database.uri);
// if (!!!mongoose.connections.length)
} catch (e) {
console.error(e);
throw createError({ statusCode: 500, message: "whoops." });
}
}

15
plugins/01.db.server.ts Normal file

@ -0,0 +1,15 @@
import mongoose from "mongoose";
import * as net from "net";
import plugnplay from "~/lib/server/plugnplay";
import { Biffno } from "~/models/challenges/biffno";
import { Ficmas } from "~/models/challenges/ficmas";
import { Challenge } from "~/models/challenges/gen";
export default defineNuxtPlugin({
name: "mongo",
// enforce: 'pre',
async setup(nuxtApp) {
// net.setDefaultAutoSelectFamily(true)
console.log("plugin->connecting........");
await plugnplay();
},
});

@ -1,19 +1,8 @@
import mongoose from "mongoose"
import {Ficmas} from "~/models/challenges/ficmas"
import {Challenge} from "~/models/challenges/gen"
import {Biffno} from "~/models/challenges/biffno"
export default eventHandler(async (event) => {
let beep = useRuntimeConfig()
console.log(beep)
Challenge;
Biffno;
Ficmas;
try {
console.log("connecting........")
await mongoose.connect(beep.database.uri)
} catch(e) {
console.error(e)
throw createError({statusCode: 500, message: "whoops."})
}
})
import mongoose from "mongoose";
import plugnplay from "~/lib/server/plugnplay";
export default eventHandler(async (event) => {
console.log("mid->connecting........");
await plugnplay();
});