Skip to content

Instantly share code, notes, and snippets.

@HectorBlisS
Created May 14, 2022 23:45
Show Gist options
  • Save HectorBlisS/b4bce717352c288062ca182be5e4a45e to your computer and use it in GitHub Desktop.
Save HectorBlisS/b4bce717352c288062ca182be5e4a45e to your computer and use it in GitHub Desktop.
import mongoose from 'mongoose';
// import for model registration
import Video from '~/db/models/Video';
import Course from '~/db/models/Course';
import User from '~/db/models/User';
import Offer from '~/db/models/Offer';
import Module from '~/db/models/Module';
import Order from '~/db/models/Order';
import { getSession } from '~/sessions';
import { redirect } from 'remix';
let mongooseClient: Object | void;
// this is a promise
const getClient = () => mongoose.connect(process.env.DB || '').catch(e => console.error(e));
// add models here
const getModels = () => ({
Course,
Module,
Video,
User,
Offer,
Order,
});
const getUsableObject = (client: Object) => ({ ...client, ...getModels() });
const dbConnection = async () => {
if (process.env.NODE_ENV === 'development') {
if (!global.mongooseClient) {
mongooseClient = await getClient();
global.mongooseClient = mongooseClient;
return getUsableObject(mongooseClient);
} else {
mongooseClient = global.mongooseClient;
return getUsableObject(mongooseClient);
}
}
mongooseClient = await getClient();
return getUsableObject(mongooseClient);
};
export const getUserOrRedirect = async (request: Request, config = { redirect: '/login' }) => {
const cookie = request.headers.get('cookie');
const session = await getSession(cookie);
if (session.has('userId')) {
const userId = session.get('userId');
const db = await dbConnection();
const user = await db.User.findById(userId);
return user;
} else {
throw redirect(config.redirect);
}
};
export default dbConnection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment