Skip to content

Commit

Permalink
Merge 49d85be into 66a874b
Browse files Browse the repository at this point in the history
  • Loading branch information
dinorhythms committed Sep 4, 2019
2 parents 66a874b + 49d85be commit 26d0971
Show file tree
Hide file tree
Showing 12 changed files with 399 additions and 2 deletions.
64 changes: 64 additions & 0 deletions src/controllers/chatController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import models from '../models';
import response from '../utils/response';
import DbServices from '../services/dbServices';
import messages from '../utils/messages';
import pushChatToFront from '../services/chatServices';

const { Chat, User } = models;
const { serverError, chatAdded } = messages;
const { getAllRecord, create, getById } = DbServices;

/**
* get all chat message in controller
* @param {Object} req - server request
* @param {Object} res - server response
* @returns {Object} - custom response
*/
const getAllChat = async (req, res) => {
try {
const options = {
order: [
['createdAt', 'ASC']
],
include: [{
model: User,
as: 'sender',
attributes: ['id', 'firstName', 'lastName', 'email', 'phoneNo']
}],
attributes: { exclude: ['userId'] }
};
const chats = await getAllRecord(Chat, options);
return response(res, 200, 'success', chats);
} catch (error) {
return response(res, 500, 'error', serverError);
}
};

/**
* insert chat message in controller
* @param {Object} req - server request
* @param {Object} res - server response
* @returns {Object} - custom response
*/
const postChat = async (req, res) => {
try {
const { id: userId } = req.decoded;
const { message } = req.body;
const chat = await create(Chat, { userId, message });
const userDetails = await getById(User, userId, { attributes: ['id', 'firstName', 'lastName', 'email', 'phoneNo'] });
const sender = {
firstName: userDetails.firstName,
lastName: userDetails.lastName,
email: userDetails.email,
phoneNo: userDetails.phoneNo
};
pushChatToFront(message, sender, chat.createdAt);
return response(res, 200, 'success', { message: chatAdded });
} catch (error) {
return response(res, 500, 'error', serverError);
}
};

export default {
getAllChat, postChat
};
39 changes: 39 additions & 0 deletions src/database/migrations/20190902172851-chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';

module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Chats', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
},
userId: {
type: Sequelize.UUID,
allowNull: false,
references: {
model: 'Users',
key: 'id',
},
},
message: {
type: Sequelize.TEXT,
allowNull: false
},
createdAt: {
allowNull: true,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('NOW')
},
updatedAt: {
allowNull: true,
type: Sequelize.DATE,
defaultValue: Sequelize.fn('NOW')
}
});
},

down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Chats');
}
};
22 changes: 22 additions & 0 deletions src/models/chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export default (sequelize, DataTypes) => {
const Chat = sequelize.define('Chat', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
message: {
type: DataTypes.TEXT,
allowNull: false,
},
}, {});

Chat.associate = (models) => {
Chat.belongsTo(models.User, {
foreignKey: 'userId',
as: 'sender'
});
};
return Chat;
};
131 changes: 131 additions & 0 deletions src/routes/api/chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import chatController from '../../controllers/chatController';
import { checkToken } from '../../middlewares/userMiddlewares';
import validate from '../../middlewares/validator';
import chatSchema from '../../validation/chatSchema';

const { getAllChat, postChat } = chatController;
const { chatPostSchema } = chatSchema;

const chatRoutes = (router) => {
router.route('/chat')
/**
* @swagger
* components:
* schemas:
* ChatUser:
* properties:
* email:
* type: string
* firstName:
* type: string
* lastName:
* type: string
* phoneNo:
* type: string
* ChatResponse:
* properties:
* id:
* type: string
* readOnly: true
* sender:
* type: string
* formal: uuid
* message:
* type: string
* createdAt:
* type: string
* format: date-time
* readOnly: true
* updateAt:
* type: string
* format: date-time
* readOnly: true
* User:
* type: array
* items:
* $ref: '#/components/schemas/ChatUser'
* ErrorResponse:
* properties:
* status:
* type: string
* example: error
* data:
* type: object
*/
/**
* @swagger
* /api/v1/chat:
* get:
* tags:
* - Chats
* description: Get all chats
* produces:
* - application/json
* responses:
* 200:
* description: Get all chats was successful
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* example: success
* data:
* type: array
* description: array of chats
* items:
* $ref: '#/components/schemas/ChatResponse'
* 403:
* description: Unauthorized
* 500:
* description: Internal Server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* security:
* - bearerAuth: []
*/
.get(checkToken, getAllChat);

router.route('/chat')
/**
* @swagger
* components:
* schemas:
* Chat:
* properties:
* message:
* type: string
*/

/**
* @swagger
* /api/v1/chat:
* post:
* tags:
* - Chats
* description: Create a new chat message
* produces:
* - application/json
* requestBody:
* description: Chat data object
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Chat'
* responses:
* 200:
* description: Your message was pushed successfully
* 500:
* description: Internal Server error
* security:
* - bearerAuth: []
*/
.post(checkToken, validate(chatPostSchema), postChat);
};

export default chatRoutes;
5 changes: 4 additions & 1 deletion src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import userRoute from './api/user';
import requestRoute from './api/request';
import notificationRoutes from './api/notification';
import authRoute from './api/auth';
import chatRoutes from './api/chat';

const routes = (router) => {
router
Expand Down Expand Up @@ -44,10 +45,12 @@ const routes = (router) => {
userRoute(router);
// request routes
requestRoute(router);
// request routes
// notification routes
notificationRoutes(router);
// social auth routes
authRoute(router);
// chat routes
chatRoutes(router);
};

export default routes;
14 changes: 14 additions & 0 deletions src/services/chatServices.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import client from '../config/pusher';

/**
* Helper function to send chat update to browser through pusher
* @param {String} message - message
* @param {String} sender - sender's details
* @param {Date} createdAt - notification body
* @returns {VoidFunction} - pusher
*/
const pushChatToFront = (message, sender, createdAt) => client.trigger('chatroom', 'message', {
message, sender, createdAt
});

export default pushChatToFront;
10 changes: 10 additions & 0 deletions src/services/dbServices.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ const DbServices = {
return model.findAndCountAll(options);
},

/**
* @param {object} model model /table
* @param {object} options query options
* @returns {Promise} Promise resolved or rejected
* @description gets all items that fit the criteria and returns rows and count
*/
getAllRecord(model, options) {
return model.findAll(options);
},

/**
* Database create service funcion
* @param {Object} model - Defined model
Expand Down
11 changes: 11 additions & 0 deletions src/test/mockData/chatMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default {
validChat: {
message: 'my trip to abuja was awesome. Thanks to Sharaton Hotel Abuja',
},
badChatMessage: {
wrongmessage: 'my trip to abuja was awesome. Thanks to Sharaton Hotel Abuja',
},
emptyChatMessage: {
message: '',
}
};
2 changes: 2 additions & 0 deletions src/test/mockData/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import userMock from './userMock';
import requestMock from './requestMock';
import roleMock from './roleMock';
import chatMock from './chatMock';

export default {
userMock,
requestMock,
roleMock,
chatMock
};
Loading

0 comments on commit 26d0971

Please sign in to comment.