Skip to content

Commit

Permalink
Merge pull request #27 from mitaai/blms/issue26
Browse files Browse the repository at this point in the history
Create Document and Group POST, PATCH routes
  • Loading branch information
mbogo-mit authored Jul 22, 2020
2 parents 9b5af26 + c093251 commit 1b4650d
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 16 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": ["airbnb", "plugin:testing-library/react"],
"plugins": ["jest","testing-library"],
"parserOptions": {
"ecmaVersion": 8,
"ecmaVersion": 9,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
Expand Down
117 changes: 116 additions & 1 deletion src/pages/api/document/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@ const handler = nc()
await req.db
.collection('documents')
.findOne(
{ _id: ObjectID(req.query.id) },
{
_id: ObjectID(req.query.id),
$or: [{ 'groups.members.id': ObjectID(token.user.id) }, { owner: ObjectID(token.user.id) }],
},
(err, doc) => {
if (doc) {
const {
title,
slug,
owner,
groups,
resourceType,
Expand All @@ -41,11 +45,14 @@ const handler = nc()
issue,
pageNumbers,
publication,
series,
sesiesNumber,
notes,
} = doc;
if (err) throw err;
res.status(200).json({
title,
slug,
owner,
groups,
resourceType,
Expand All @@ -68,6 +75,8 @@ const handler = nc()
issue,
pageNumbers,
publication,
series,
sesiesNumber,
notes,
});
} else {
Expand All @@ -77,6 +86,112 @@ const handler = nc()
);
} else res.status(403).json({ error: '403 Invalid or expired token' });
},
)
.patch(
async (req, res) => {
const token = await jwt.getJwt({ req, secret });
if (token && token.exp > 0) {
const {
title,
slug,
resourceType,
authors,
publisher,
publicationDate,
bookTitle,
edition,
url,
accessed,
rightsStatus,
location,
state,
text,
editors,
volume,
issue,
pageNumbers,
publication,
series,
sesiesNumber,
notes,
} = req.body;
const fieldsToSet = {
title,
slug,
resourceType,
authors,
publisher,
publicationDate,
bookTitle,
edition,
url,
accessed,
rightsStatus,
location,
state,
text,
editors,
volume,
issue,
pageNumbers,
publication,
series,
sesiesNumber,
notes,
};
Object.keys(fieldsToSet).forEach((key) => {
if (fieldsToSet[key] === undefined) {
delete fieldsToSet[key];
}
});
const groupToPush = req.body.addedGroup
? { groups: req.body.addedGroup }
: {};
const groupToPull = req.body.removedGroupId
? { 'groups.id': ObjectID(req.body.removedGroupId) }
: {};
let groupById = {};
let groupFieldsToSet = {};
let memberToPush = {};
let memberToPull = {};
if (req.body.updatedGroup) {
groupById = { 'groups.id': ObjectID(req.body.updatedGroup.id) };
if (req.body.updatedGroup.name) {
groupFieldsToSet = { 'groups.$.name': req.body.updatedGroup.name };
}
if (req.body.addedUser) {
memberToPush = { 'groups.$.members': req.body.addedUser };
}
if (req.body.removedUserId) {
memberToPull = { 'groups.$.members.id': ObjectID(req.body.removedUserId) };
}
}
await req.db
.collection('documents')
.findOneAndUpdate(
{
_id: ObjectID(req.query.id),
owner: ObjectID(token.user.id),
...groupById,
},
{
$set: { ...fieldsToSet, ...groupFieldsToSet },
$push: { ...memberToPush, ...groupToPush },
$pull: { ...memberToPull, ...groupToPull },
$currentDate: {
updatedAt: true,
},
},
{
returnOriginal: false,
},
(err, doc) => {
if (err) throw err;
res.status(200).json(doc);
},
);
} else res.status(403).json({ error: '403 Invalid or expired token' });
},
);

export default handler;
90 changes: 90 additions & 0 deletions src/pages/api/document/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import nc from 'next-connect';
import { ObjectID } from 'mongodb';
import jwt from 'next-auth/jwt';
import middleware from '../../../middlewares/middleware';

const secret = process.env.AUTH_SECRET;

const handler = nc()
.use(middleware)
.post(
async (req, res) => {
const token = await jwt.getJwt({ req, secret });
if (token && token.exp > 0) {
const dateCreated = new Date(Date.now());
const {
title,
slug,
groups,
resourceType,
authors,
publisher,
publicationDate,
bookTitle,
edition,
url,
accessed,
rightsStatus,
location,
state,
text,
uploadContentType,
editors,
volume,
issue,
pageNumbers,
publication,
series,
sesiesNumber,
notes,
} = req.body;
const metadata = {
title,
slug,
groups,
resourceType,
authors,
publisher,
publicationDate,
bookTitle,
edition,
url,
accessed,
rightsStatus,
location,
state,
text,
uploadContentType,
editors,
volume,
issue,
pageNumbers,
publication,
series,
sesiesNumber,
notes,
};
Object.keys(metadata).forEach((key) => {
if (metadata[key] === undefined) {
delete metadata[key];
}
});
await req.db
.collection('documents')
.insert(
{
owner: ObjectID(token.user.id),
createdAt: dateCreated,
updatedAt: dateCreated,
...metadata,
},
(err, doc) => {
if (err) throw err;
res.status(200).json(doc);
},
);
} else res.status(403).json({ error: '403 Invalid or expired token' });
},
);

export default handler;
49 changes: 38 additions & 11 deletions src/pages/api/group/[id].js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/* eslint-disable max-len */
import nc from 'next-connect';
import { ObjectID } from 'mongodb';
import jwt from 'next-auth/jwt';
import middleware from '../../../middlewares/middleware';

const secret = process.env.AUTH_SECRET;
const fakeUserId = ObjectID('7b639ae33efb36eaf6447c55');

const handler = nc()
.use(middleware)
Expand All @@ -17,7 +17,7 @@ const handler = nc()
.findOne(
{
_id: ObjectID(req.query.id),
members: token.user.id,
'members.id': ObjectID(token.user.id),
},
(err, doc) => {
if (doc) {
Expand All @@ -39,27 +39,54 @@ const handler = nc()
} else {
res.status(404).json({ error: '404 Not Found' });
}
},
)
},
);
}
},
)
.patch(
async (req, res) => {
const token = await jwt.getJwt({ req, secret });
if (token && token.exp > 0) {
const memberQuery = (process.env.NODE_ENV === 'development') ? [{ members: ObjectID(token.user.id) }, { members: getObjectId('FakeUserReplaceMe') }] : [{ members: ObjectID(token.user.id) }];
const fieldsToSet = req.body.name ? { name: req.body.name } : {};
const membersToPush = req.body.addedUserId ? { members: ObjectID(req.body.addedUserId) } : {};
const membersToPull = req.body.removedUserId ? { members: ObjectID(req.body.removedUserId) } : {};
const memberQuery = (process.env.NODE_ENV === 'development')
? [{ 'members.id': ObjectID(token.user.id) }, { 'members.id': fakeUserId }]
: [{ 'members.id': ObjectID(token.user.id) }];
const nameToUpdate = req.body.name
? { name: req.body.name }
: {};
let documentToUpdate = {};
let documentById = {};
if (req.body.updatedDocument) {
documentById = { 'documents.id': ObjectID(req.body.updatedDocument.id) };
documentToUpdate = {
'documents.$.slug': req.body.updatedDocument.slug,
'documents.$.name': req.body.updatedDocument.name,
};
}
const memberToPush = req.body.addedUser
? { members: req.body.addedUser }
: {};
const documentToPush = req.body.addedDocument
? { documents: req.body.addedDocument }
: {};
const memberToPull = req.body.removedUserId
? { 'members.id': ObjectID(req.body.removedUserId) }
: {};
const documentToPull = req.body.removedDocumentId
? { 'documents.id': ObjectID(req.body.removedDocumentId) }
: {};
await req.db
.collection('groups')
.findOneAndUpdate(
{
_id: ObjectID(req.query.id),
$or: memberQuery,
...documentById,
},
{
$set: fieldsToSet,
$push: membersToPush,
$pull: membersToPull,
$set: { ...nameToUpdate, ...documentToUpdate },
$push: { ...memberToPush, ...documentToPush },
$pull: { ...memberToPull, ...documentToPull },
$currentDate: {
updatedAt: true,
},
Expand Down
35 changes: 35 additions & 0 deletions src/pages/api/group/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import nc from 'next-connect';
import { ObjectID } from 'mongodb';
import jwt from 'next-auth/jwt';
import middleware from '../../../middlewares/middleware';

const secret = process.env.AUTH_SECRET;

const handler = nc()
.use(middleware)
.post(
async (req, res) => {
const token = await jwt.getJwt({ req, secret });
if (token && token.exp > 0) {
const { name } = req.body;
const members = [{
id: ObjectID(token.user.id),
name: token.user.name,
email: token.user.email,
role: 'owner',
}];
const documents = [{}];
await req.db
.collection('groups')
.insertOne(
{ name, members, documents },
(err, doc) => {
if (err) throw err;
res.status(200).json(doc);
},
);
} else res.status(403).json({ error: '403 Invalid or expired token' });
},
);

export default handler;
13 changes: 11 additions & 2 deletions src/seeds/1-groups/groups.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,17 @@ const dateCreated = new Date(Date.now());
const group = {
id: getObjectId(name),
name,
members: [getObjectId('FakeUserReplaceMe')],
documents: [getObjectId(docTitle)],
members: [{
id: getObjectId('FakeUserReplaceMe'),
name: 'Fake User',
email: '[email protected]',
role: 'owner',
}],
documents: [{
id: getObjectId(docTitle),
name: docTitle,
slug: 'afterward',
}],
createdAt: dateCreated,
updatedAt: dateCreated,
};
Expand Down
Loading

0 comments on commit 1b4650d

Please sign in to comment.