Skip to content

Commit

Permalink
Merge f1e5c3d into f0ffb70
Browse files Browse the repository at this point in the history
  • Loading branch information
wombolo committed Jan 28, 2019
2 parents f0ffb70 + f1e5c3d commit 875a3a0
Show file tree
Hide file tree
Showing 19 changed files with 490 additions and 63 deletions.
File renamed without changes.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"passport-twitter": "^1.0.4",
"pg": "^7.7.1",
"pg-hstore": "^2.3.2",
"pusher": "2.2.0",
"request": "^2.87.0",
"sequelize": "^4.42.0",
"sequelize-cli": "^5.4.0",
Expand Down
80 changes: 46 additions & 34 deletions src/controllers/ArtsController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sequelize from 'sequelize';
import models from '../db/models';
import { Response, Slugify } from '../helpers/index';
import { Response, Slugify, sendNotifications } from '../helpers/index';

const {
Art, Media, Category, User, Comment
Expand All @@ -15,38 +15,28 @@ class ArtsController {
* @param {object} res
* @memberof ArtsController
* This will receive a media object containing a list of media files
* @returns {Object} Article details
* @returns {Object} Article payloadObject
*/
static async create(req, res) {
try {
const defaultStatus = 0;
const validationErrors = [];

const { id: artistId } = req.verifyUser;

const {
title, description, categoryId, media,
title, description, categoryId,
} = req.body;

const mediaFilesArray = JSON.parse(media);

req.check('title', 'Title is required').notEmpty();
req.check('description', 'Description should be longer').notEmpty()
.isLength({ min: 15 });

const errors = req.validationErrors();
let { media } = req.body;

if (errors) {
errors.map(err => validationErrors.push(err.msg));
const response = new Response(
'Not Ok',
400,
'Validation Errors Occurred',
{ validationErrors }
);
return res.status(response.code).json(response);
if (!media) {
media = `[{
"url":"${process.env.DEFAULT_ARTICLE_IMAGE}",
"extension":"jpeg"}]`;
}

const mediaFilesArray = JSON.parse(media);

const slugifiedTitle = Slugify.slugify(title);

const checkCategory = await Category.findOne({ where: { id: 1 } });
Expand All @@ -61,8 +51,7 @@ class ArtsController {
title,
description,
categoryId,
featuredImg: mediaFilesArray[0].url
|| process.env.DEFAULT_ARTICLE_IMAGE,
featuredImg: mediaFilesArray[0].url,
status: defaultStatus
});

Expand All @@ -87,6 +76,19 @@ class ArtsController {
});
}

const notifyFollowers = new sendNotifications({
type: 'newArticle',
articleDetails: {
artId,
artistId,
artTitle,
slugifiedTitle,
artDescription,
artFeaturedImg
}
});
const followersNotified = await notifyFollowers.create();

const response = new Response(
'Ok',
201,
Expand All @@ -97,7 +99,8 @@ class ArtsController {
slugifiedTitle,
artDescription,
artFeaturedImg,
artCategoryId
artCategoryId,
followersNotified
}
);

Expand All @@ -117,7 +120,7 @@ class ArtsController {
* @param {object} req
* @param {object} res
* @memberof ArtsController
* @returns {Object} Article details
* @returns {Object} Article payloadObject
*/
static async update(req, res) {
try {
Expand Down Expand Up @@ -150,20 +153,29 @@ class ArtsController {
}

const {
title, description, categoryId, media,
title, description, categoryId,
} = req.body;


let { media } = req.body;

if (!media) {
media = `[{
"url":"${process.env.DEFAULT_ARTICLE_IMAGE}",
"extension":"jpeg"}]`;
}

const mediaFilesArray = JSON.parse(media);

req.check('title', 'Title is required').notEmpty();
req.check('description', 'Description should be longer').notEmpty()
req.check('title', 'Title is required').trim().notEmpty();
req.check('description', 'Description should be longer').trim().notEmpty()
.isLength({ min: 15 });

const errors = req.validationErrors();
if (errors) {
errors.map(err => validationErrors.push(err.msg));
const response = new Response(
'Not Ok',
'Not ok',
400,
'Validation Errors Occurred',
{ validationErrors }
Expand All @@ -175,11 +187,11 @@ class ArtsController {

const updatedArticle = {
id: artToUpdate.id,
title: title || artToUpdate.title,
title,
slug: slugifiedTitle,
description: description || artToUpdate.description,
categoryId: categoryId || artToUpdate.categoryId,
featuredImg: mediaFilesArray[0].url || artToUpdate.featuredImg,
description,
categoryId,
featuredImg: mediaFilesArray[0].url,
createdAt: artToUpdate.createdAt
};

Expand Down Expand Up @@ -222,7 +234,7 @@ class ArtsController {
* @param {object} req
* @param {object} res
* @memberof ArtsController
* @returns {Object} Article details
* @returns {number} Article Deletion status
*/
static async delete(req, res) {
try {
Expand Down Expand Up @@ -259,7 +271,7 @@ class ArtsController {

const response = new Response(
'Ok',
200,
202,
'Article deleted successfully',
{ artToDelete: artDeleted }
);
Expand Down
14 changes: 14 additions & 0 deletions src/controllers/CommentsController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import models from '../db/models';
import Response from '../helpers/response';
import { sendNotifications } from '../helpers';

const { Comment, Art, UpdatedComment } = models;

Expand Down Expand Up @@ -30,10 +31,23 @@ class CommentsController {
artId,
body
});

const notifyNewComments = new sendNotifications({
type: 'newComment',
commentDetails: {
artId,
userId: id,
body
}
});

const newCommentsNotified = await notifyNewComments.create();

const response = new Response(
'created',
201,
'Comment added successfully',
newCommentsNotified
);
return res.status(response.code).json(response);
}
Expand Down
8 changes: 4 additions & 4 deletions src/controllers/UsersController.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class UsersController {
* @param {object} req
* @param {object} res
* @memberof UsersController
* @returns user details
* @returns user payloadObject
*/
static async signUp(req, res) {
const defaultstatus = 0;
Expand Down Expand Up @@ -57,7 +57,7 @@ class UsersController {
imgURL,
});
const userDetails = {
id, registeredUsername, registeredEmail, userSignupType
id, registeredUsername, registeredEmail, userSignupType, userType
};
const token = await TokenAuthenticate
.generateToken(userDetails, tokenExpireTime);
Expand Down Expand Up @@ -132,10 +132,10 @@ class UsersController {
return res.status(response.code).json(response);
}
const {
id, username, email: userEmail, signUpType
id, username, email: userEmail, signUpType, userType
} = user;
const userDetails = {
id, username, userEmail, signUpType
id, username, userEmail, signUpType, userType
};
const token = await TokenAuthenticate
.generateToken(userDetails, tokenExpireTime);
Expand Down
39 changes: 39 additions & 0 deletions src/db/migrations/20190123120723-create-notifications.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
module.exports = {
up: (
queryInterface,
Sequelize
) => queryInterface.createTable('Notifications', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
allowNull: false,
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
references: {
model: 'Users',
key: 'id',
as: 'userId',
}
},
message: {
type: Sequelize.STRING
},
status: {
type: Sequelize.BOOLEAN
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}),
down: queryInterface => queryInterface.dropTable('Notifications')
};
1 change: 1 addition & 0 deletions src/db/models/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ module.exports = (sequelize, DataTypes) => {
});
Comment.belongsTo(models.User, {
foreignKey: 'userId',
as: 'User',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
Expand Down
16 changes: 16 additions & 0 deletions src/db/models/notifications.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = (sequelize, DataTypes) => {
const Notifications = sequelize.define('Notifications', {
userId: DataTypes.INTEGER,
message: DataTypes.STRING,
status: DataTypes.BOOLEAN
}, {});
Notifications.associate = (models) => {
Notifications.belongsTo(models.User, {
foreignKey: 'userId',
as: 'notifications',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
};
return Notifications;
};
3 changes: 1 addition & 2 deletions src/db/models/report.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

module.exports = (sequelize, DataTypes) => {
const Report = sequelize.define('Report', {
reportText: {
Expand All @@ -21,7 +20,7 @@ module.exports = (sequelize, DataTypes) => {
}
}
}, {});
Report.associate = function (models) {
Report.associate = (models) => {
// associations can be defined here
Report.belongsTo(models.Art, {
foreignKey: 'artId',
Expand Down
3 changes: 3 additions & 0 deletions src/db/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ module.exports = (sequelize, DataTypes) => {
User.hasMany(models.Report, {
foreignKey: 'userId'
});
User.hasMany(models.Notifications, {
foreignKey: 'userId'
});
};
return User;
};
5 changes: 3 additions & 2 deletions src/helpers/EmailNotificationAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ class EmailNotificationAPI {
*/
constructor(emailPayload) {
this.mailOptions = {
from: `"Merry Ah 👻" <${process.env.EMAILUSER}>`, // sender address
from: `"Merry Ah" <${process.env.EMAILUSER}>`, // sender address
to: emailPayload.recipient, // list of receivers
bcc: emailPayload.bcc,
subject: emailPayload.subject, // Subject line
text: emailPayload.message, // html body
html: `<p> ${emailPayload.message} </p>` // html body
Expand Down Expand Up @@ -47,7 +48,7 @@ class EmailNotificationAPI {
* @return {string|Object} Success message | Error
*/
async sendEmail() {
const mailOptions = this.mailOptions;
const { mailOptions } = this;
if (process.env.NODE_ENV === 'production') {
try {
const mail = await EmailNotificationAPI.transportCreator()
Expand Down
4 changes: 3 additions & 1 deletion src/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import EmailNotificationAPI from './EmailNotificationAPI';
import TokenAuthenticate from './TokenAuthenticate';
import Response from './response';
import Slugify from './Slugify';
import sendNotifications from './sendNotifications';

export {
EmailNotificationAPI,
Slugify,
TokenAuthenticate,
Response
Response,
sendNotifications
};
Loading

0 comments on commit 875a3a0

Please sign in to comment.