Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove database middleware pattern #145

Merged
merged 1 commit into from
Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions api-lib/auth/passport.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import { findUserForAuth, findUserWithEmailAndPassword } from '@/api-lib/db';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
import { getMongoDb } from '../mongodb';

passport.serializeUser((user, done) => {
done(null, user._id);
});

passport.deserializeUser((req, id, done) => {
findUserForAuth(req.db, id).then(
(user) => done(null, user),
(err) => done(err)
);
getMongoDb().then((db) => {
findUserForAuth(db, id).then(
(user) => done(null, user),
(err) => done(err)
);
});
});

passport.use(
new LocalStrategy(
{ usernameField: 'email', passReqToCallback: true },
async (req, email, password, done) => {
const user = await findUserWithEmailAndPassword(req.db, email, password);
const db = await getMongoDb();
const user = await findUserWithEmailAndPassword(db, email, password);
if (user) done(null, user);
else done(null, false, { message: 'Email or password is incorrect' });
}
Expand Down
1 change: 0 additions & 1 deletion api-lib/mail.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export async function sendMail({ from, to, subject, html }) {
html,
});
} catch (e) {
console.error(e);
throw new Error(`Could not send email: ${e.message}`);
}
}
Expand Down
50 changes: 0 additions & 50 deletions api-lib/middlewares/database.js

This file was deleted.

1 change: 0 additions & 1 deletion api-lib/middlewares/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export { validateBody } from './ajv';
export { default as auths } from './auth';
export { default as database } from './database';
2 changes: 1 addition & 1 deletion api-lib/middlewares/session.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getMongoClient } from '@/api-lib/mongodb';
import MongoStore from 'connect-mongo';
import nextSession from 'next-session';
import { promisifyStore } from 'next-session/lib/compat';
import { getMongoClient } from './database';

const mongoStore = MongoStore.create({
clientPromise: getMongoClient(),
Expand Down
46 changes: 46 additions & 0 deletions api-lib/mongodb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { MongoClient } from 'mongodb';

let indexesCreated = false;
async function createIndexes(client) {
if (indexesCreated) return client;
const db = client.db();
await Promise.all([
db
.collection('tokens')
.createIndex({ expireAt: -1 }, { expireAfterSeconds: 0 }),
db
.collection('posts')
.createIndexes([{ key: { createdAt: -1 } }, { key: { creatorId: -1 } }]),
db
.collection('comments')
.createIndexes([{ key: { createdAt: -1 } }, { key: { postId: -1 } }]),
db.collection('users').createIndexes([
{ key: { email: 1 }, unique: true },
{ key: { username: 1 }, unique: true },
]),
]);
indexesCreated = true;
return client;
}

export async function getMongoClient() {
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentiatlly
* during API Route usage.
* https://github.com/vercel/next.js/pull/17666
*/
if (!global.mongoClientPromise) {
const client = new MongoClient(process.env.MONGODB_URI);
// client.connect() returns an instance of MongoClient when resolved
global.mongoClientPromise = client
.connect()
.then((client) => createIndexes(client));
}
return global.mongoClientPromise;
}

export async function getMongoDb() {
const mongoClient = await getMongoClient();
return mongoClient.db();
}
4 changes: 2 additions & 2 deletions pages/api/auth.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { passport } from '@/api-lib/auth';
import { auths, database } from '@/api-lib/middlewares';
import { auths } from '@/api-lib/middlewares';
import { ncOpts } from '@/api-lib/nc';
import nc from 'next-connect';

const handler = nc(ncOpts);

handler.use(database, ...auths);
handler.use(...auths);

handler.post(passport.authenticate('local'), (req, res) => {
res.json({ user: req.user });
Expand Down
17 changes: 10 additions & 7 deletions pages/api/posts/[postId]/comments/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { ValidateProps } from '@/api-lib/constants';
import { findPostById } from '@/api-lib/db';
import { findComments, insertComment } from '@/api-lib/db/comment';
import { auths, database, validateBody } from '@/api-lib/middlewares';
import { auths, validateBody } from '@/api-lib/middlewares';
import { getMongoDb } from '@/api-lib/mongodb';
import { ncOpts } from '@/api-lib/nc';
import nc from 'next-connect';

const handler = nc(ncOpts);

handler.use(database);

handler.get(async (req, res) => {
const post = await findPostById(req.db, req.query.postId);
const db = await getMongoDb();

const post = await findPostById(db, req.query.postId);

if (!post) {
return res.status(404).json({ error: { message: 'Post is not found.' } });
}

const comments = await findComments(
req.db,
db,
req.query.postId,
req.query.before ? new Date(req.query.before) : undefined,
req.query.limit ? parseInt(req.query.limit, 10) : undefined
Expand All @@ -41,15 +42,17 @@ handler.post(
return res.status(401).end();
}

const db = await getMongoDb();

const content = req.body.content;

const post = await findPostById(req.db, req.query.postId);
const post = await findPostById(db, req.query.postId);

if (!post) {
return res.status(404).json({ error: { message: 'Post is not found.' } });
}

const comment = await insertComment(req.db, post._id, {
const comment = await insertComment(db, post._id, {
creatorId: req.user._id,
content,
});
Expand Down
13 changes: 8 additions & 5 deletions pages/api/posts/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { ValidateProps } from '@/api-lib/constants';
import { findPosts, insertPost } from '@/api-lib/db';
import { auths, database, validateBody } from '@/api-lib/middlewares';
import { auths, validateBody } from '@/api-lib/middlewares';
import { getMongoDb } from '@/api-lib/mongodb';
import { ncOpts } from '@/api-lib/nc';
import nc from 'next-connect';

const handler = nc(ncOpts);

handler.use(database);

handler.get(async (req, res) => {
const db = await getMongoDb();

const posts = await findPosts(
req.db,
db,
req.query.before ? new Date(req.query.before) : undefined,
req.query.by,
req.query.limit ? parseInt(req.query.limit, 10) : undefined
Expand All @@ -34,7 +35,9 @@ handler.post(
return res.status(401).end();
}

const post = await insertPost(req.db, {
const db = await getMongoDb();

const post = await insertPost(db, {
content: req.body.content,
creatorId: req.user._id,
});
Expand Down
9 changes: 6 additions & 3 deletions pages/api/user/email/verify.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { createToken } from '@/api-lib/db';
import { CONFIG as MAIL_CONFIG, sendMail } from '@/api-lib/mail';
import { auths, database } from '@/api-lib/middlewares';
import { auths } from '@/api-lib/middlewares';
import { getMongoDb } from '@/api-lib/mongodb';
import { ncOpts } from '@/api-lib/nc';
import nc from 'next-connect';

const handler = nc(ncOpts);

handler.use(database, ...auths);
handler.use(...auths);

handler.post(async (req, res) => {
if (!req.user) {
res.json(401).end();
return;
}

const token = await createToken(req.db, {
const db = await getMongoDb();

const token = await createToken(db, {
creatorId: req.user._id,
type: 'emailVerify',
expireAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
Expand Down
12 changes: 8 additions & 4 deletions pages/api/user/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ValidateProps } from '@/api-lib/constants';
import { findUserByUsername, updateUserById } from '@/api-lib/db';
import { auths, database, validateBody } from '@/api-lib/middlewares';
import { auths, validateBody } from '@/api-lib/middlewares';
import { getMongoDb } from '@/api-lib/mongodb';
import { ncOpts } from '@/api-lib/nc';
import { slugUsername } from '@/lib/user';
import { v2 as cloudinary } from 'cloudinary';
Expand All @@ -24,7 +25,7 @@ if (process.env.CLOUDINARY_URL) {
});
}

handler.use(database, ...auths);
handler.use(...auths);

handler.get(async (req, res) => {
if (!req.user) return res.json({ user: null });
Expand All @@ -47,6 +48,9 @@ handler.patch(
req.status(401).end();
return;
}

const db = await getMongoDb();

let profilePicture;
if (req.file) {
const image = await cloudinary.uploader.upload(req.file.path, {
Expand All @@ -64,7 +68,7 @@ handler.patch(
username = slugUsername(req.body.username);
if (
username !== req.user.username &&
(await findUserByUsername(req.db, username))
(await findUserByUsername(db, username))
) {
res
.status(403)
Expand All @@ -73,7 +77,7 @@ handler.patch(
}
}

const user = await updateUserById(req.db, req.user._id, {
const user = await updateUserById(db, req.user._id, {
...(username && { username }),
...(name && { name }),
...(typeof bio === 'string' && { bio }),
Expand Down
10 changes: 7 additions & 3 deletions pages/api/user/password/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { ValidateProps } from '@/api-lib/constants';
import { updateUserPasswordByOldPassword } from '@/api-lib/db';
import { auths, database, validateBody } from '@/api-lib/middlewares';
import { auths, validateBody } from '@/api-lib/middlewares';
import { getMongoDb } from '@/api-lib/mongodb';
import { ncOpts } from '@/api-lib/nc';
import nc from 'next-connect';

const handler = nc(ncOpts);
handler.use(database, ...auths);
handler.use(...auths);

handler.put(
validateBody({
Expand All @@ -22,10 +23,13 @@ handler.put(
res.json(401).end();
return;
}

const db = await getMongoDb();

const { oldPassword, newPassword } = req.body;

const success = await updateUserPasswordByOldPassword(
req.db,
db,
req.user._id,
oldPassword,
newPassword
Expand Down
Loading