Skip to content

Instantly share code, notes, and snippets.

@shiningnicholson95
Last active September 11, 2019 11:03
Show Gist options
  • Save shiningnicholson95/3665cfe7fb6ea58e902573cb4151f470 to your computer and use it in GitHub Desktop.
Save shiningnicholson95/3665cfe7fb6ea58e902573cb4151f470 to your computer and use it in GitHub Desktop.
Sample Assignment of Notes - SmartHub Project.

Sample Assignment

Creating a sample notes assignment

Problem Statement

The objective is to create a new entity called "notes" in the codebase. We would do the following:

  1. Creation of model(schema) for notes, giving it attributes like title, description and status.
  2. Providing appropriate "Seeds"(dummy data) for the "notes" model.
  3. Creation of appropriate "Routes" for the "notes" in order to provide appropriate paths for carrying out operations.
  4. Creation of "Services".
  5. Creation of "Controllers"
  6. Creating appropriate "View"
  7. Performing CRUD operations for "notes".

Models

Models act as schema for representing the information for a particular table to be inserted into the document. We are using the model structure defined by Sequelize(https://sequelize.org/) here. Create a model called "notes.js" under the “models” folder in your smarthub project folder.

Seeds

Seeding is basically providing dummy data that can be stored in the "notes" table in the database if before any information can be inserted by the user. Navigate to the "seed" folder in your smarthub project. create a new seed file called "notes.json" and enter some dummy data in JSON format.

Routes

Routes provide the pathway for various operations to be performed within the project. Create a file called notes.routes.js under the "routes" folder in smarthub project. Also provide application router by the name of "noteRouter" in the app.js file of the smarthub project.

Services

We need to create services that facilitate the operations we are going to perform. Create a service called noteService.js under the "services" folder in your smarthub_ch project.

Controllers

Controllers are used for rendering the data onto the client. Create a file called "notesControllers.js" under the "controllers" folder in the smarthub_ch project.

View Layer

View Layer will render all our back-end logic to the client-side. In the smarthub project, for view layer, we will have to make certain changes for the "notes". Following is the list of files we need to make changes to:

navigationConfig.json

We need to add our notes menu to the navigation dashboard of smarthub project. Add the following piece of code in the navigationConfig.json file.

"notesMenu": {
        "display": "none",
        "subMenuState": {
            "Notes": ""
        }
    }

acl.json

acl.json file facilitates that there is notes menu present in the navigation dashboard. add "notesMenu" key under the "navigation" object in acl.json file.

   "navigation": {
            "dashboardsMenu": true,
            "partnerCharitiesMenu": true,
            "vendingMachinesMenu": true,
            "clientsMenu": true,
            "employeesMenu": true,
            "jobsMenu": true,
            "donationsMenu": true,
            "superAdminMenu": true,
            "cmssMenu": true,
            "pimMenu": true,
            "notesMenu": true // newly added notesMenu
        }

default.hbs

default.hbs is the main rendering page of the smarthub. Here it will render the views of all layers. We need to add notesMenu here as well.

<!--Dashboards-->
 {{#if loggedInUser.navigationRules.notesMenu}}
     {{> navigation/notesMenu this}}
  {{/if}}

the above layers facilitate the rendering of your particular table data(in this case, notes) on the client-side.

Creating user-made view layers

under the "views" section, we need to have self-defined view layers for various operations, that is creating a new note, reading the notes, and deleting the notes.

  1. create "notes" folder under the "views" folder in smarthub.
  2. create "getNotes.hbs" file for reading all notes in the dashboard.
  3. create "createNotes.hbs" file for creating a new note.
module.exports = function(sequelize, DataTypes) {
var notes = sequelize.define('notes', {
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
title:{
type: DataTypes.STRING(255),
allowNull: false,
},
description: {
type: DataTypes.STRING(200),
allowNull: false
}
}, {
tableName: 'notes'
});
return notes;
};
[
{
"model": "notes",
"data": {
"id": 1,
"title": "Drinks",
"description": "sample note number 1",
"status": "posted",
}
},
{
"model": "notes",
"data": {
"id": 2,
"title": "Utilities",
"description": "sample note number 2",
"status": "posted"
}
}
]
const router = require('express').Router();
const genericController = require("../controllers/genericController");
const notesController = require("../controllers/notesController");
router.get('/getNotes', genericController.isAuthenticated, notesController.renderNotesPage);
router.get('/createNotes',genericController.isAuthenticated, notesController.renderCreateNotesPage)
router.post('/createNotes',genericController.isAuthenticated, notesController.createNotes);
router.post('/delete/:code',genericController.isAuthenticated,notesController.deleteNote);
module.exports = router;
var logger = require('../helpers/logger')
const models = require('../models');
const getNotes = function() {
const notes = models.notes;
return notes.findAll({
attributes: {
exclude: ['createdAt', 'updatedAt']
},
order: [
['description','ASC'],
]
}).then(function(notes) {
console.log('Display',notes);
return notes
}).catch(function(err) {
logger.error('Something went werong fetching the notes' + err)
});
}
const deleteNote = function (code) {
const Note = models.notes;
return Note.destroy({
where: {
id: code
}
}).then(function (deletedRecord) {
if (deletedRecord === 1) {
return { success: true, message: 'Note deleted successfully!' }
} else {
return { success: false, message: 'Note was not deleted!' }
}
}).catch(function (err) {
logger.error('Something went wrong while deleting the Note' + err)
return { success: false, message: 'There was an error deleting the Note!' }
})
}
const createNotes = (data) => {
const note = models.notes;
return note.create(data)
.then((result) => {
const responseData = {};
logger.info('Note created successfully!');
responseData.status = 'success';
responseData.data = result.dataValues;
return responseData;
})
.catch((error) => {
logger.error(`Something went wrong with this operation${error}`);
});
};
module.exports = {
"getNotes": getNotes,
"createNotes":createNotes,
"deleteNote": deleteNote
}
const logger = require('../helpers/logger');
const noteService = require('../services/noteService');
const { check, validationResult } = require('express-validator/check');
const navigationConfig = require('../config/navigationConfig.json');
const createNotesForm = require('../config/forms/createNotesForm.json')
const renderNotesPage = async (req, res) => {
const navigationConfigClone = JSON.parse(JSON.stringify(navigationConfig));
navigationConfigClone.notesMenu.display = 'block';
navigationConfigClone.notesMenu.subMenuState.Notes = 'active';
res.render('notes/getNotes', {
navigationConfig: navigationConfigClone,
notes: await noteService.getNotes()
});
};
const deleteNote = async (req, res, next) => {
let result = await noteService.deleteNote(
req.params.code,
);
return res.status(200).json(result);
};
const renderCreateNotesPage = (req, res) => {
const navigationConfigClone = JSON.parse(JSON.stringify(navigationConfig));
navigationConfigClone.notesMenu.display = 'block';
navigationConfigClone.notesMenu.subMenuState.Notes = 'active';
res.render('notes/createNotes', {
navigationConfig: navigationConfigClone,
formJSON: JSON.stringify(createNotesForm),
isEditMode: false,
});
};
const createNotes = async (req, res) => {
const data = {};
data.title = req.body.title;
data.description = req.body.description;
data.status = req.body.status;
console.log( ' Title = ', data.title);
console.log( ' Description = ', data.description);
console.log( ' Status = ', data.status);
const result = await noteService.createNotes(data);
if (result && result.status === 'success') {
req.session.sessionFlash = {
type: 'success',
message: 'Note created successfully',
};
res.redirect('/notes/getNotes')
res.json(result);
} else {
req.session.sessionFlash = {
type: 'error',
message: 'Failed to create Notes',
};
res.json(result);
// res.redirect('/notes/productNotes')
}
};
module.exports = {
'renderNotesPage':renderNotesPage,
'renderCreateNotesPage': renderCreateNotesPage,
'createNotes':createNotes,
"deleteNote":deleteNote
}
<div class="g-pa-20">
<header class="g-mb-20">
<h2 class="g-color-black mb-0">Notes</h2>
</header>
<div class="media-md align-items-center g-mb-30">
<div><a href="/notes/createNotes" class="btn btn-md btn-xl--md u-btn-secondary g-font-size-12 g-font-size-default--md g-mb-10" >
Create Notes</a></div>
{{>navigation/search}}
</div>
<div class="table-responsive g-mb-40">
<table class="js-datatable table table-striped u-table--v3 u-editable-table--v1 g-color-black"
{{>navigation/dataTableConfig}}>
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{{#each notes}}
<tr>
<td>{{id}}</td>
<td>{{title}}</td>
<td>{{description}}</td>
<td>
<div class="g-pos-rel g-top-3 d-inline-block">
<a id="dropDown{{id}}Invoker" class="u-link-v5 g-line-height-0 g-font-size-24 g-color-gray-light-v6
g-color-secondary--hover" href="#!" aria-controls="dropDown{{id}}"
aria-haspopup="true" aria-expanded="false" data-dropdown-event="click"
data-dropdown-target="#dropDown{{id}}">
<i class="hs-admin-more-alt"></i>
</a>
<div id="dropDown{{id}}"
class="u-shadow-v31 g-pos-abs g-right-0 g-z-index-2 g-bg-white
u-dropdown--css-animation u-dropdown--hidden u-dropdown--reverse-y"
aria-labelledby="dropDown{{id}}Invoker">
<ul class="list-unstyled g-nowrap mb-0">
<li>
<a class="d-flex align-items-center u-link-v5
g-bg-gray-light-v8--hover g-font-size-12 g-font-size-default--md
g-color-gray-dark-v6 g-px-25 g-py-14" href="/notes/editNotes/{{id}}">
<i class="hs-admin-pencil g-font-size-18 g-color-gray-light-v6 g-mr-10 g-mr-15--md"></i>
Edit
</a>
</li>
{{!-- <li>
<a class="d-flex align-items-center
u-link-v5 g-bg-gray-light-v8--hover g-font-size-12
g-font-size-default--md g-color-gray-dark-v6 g-px-25 g-py-14"
href="/vendingMachines/duplicate/{{id}}">
<i class="hs-admin-pencil g-font-size-18 g-color-gray-light-v6 g-mr-10 g-mr-15--md"></i>
Duplicate
</a>
</li> --}}
<li>
<a class="delete-item d-flex align-items-center u-link-v5
g-bg-gray-light-v8--hover g-font-size-12 g-font-size-default--md
g-color-gray-dark-v6 g-px-25 g-py-14" href="/notes/delete/{{id}}">
<i class="hs-admin-trash g-font-size-18 g-color-gray-light-v6 g-mr-10 g-mr-15--md"></i>
Delete
</a>
</li>
</ul>
</div>
</div>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
{{>navigation/pagination}}
</div>
<script type = 'text/javascript' > //Defining form elements, Putting in JSON and rendering it.
window.onload = function () {
const template = 'bootstrap4';
Formio.createForm(document.getElementById('form'), {{{formJSON}}}, {
template: template
}).then(function (item) {
form = item;
form.on('submit', function(submission) {
{{!-- console.log('submission -> ', JSON.stringify(submission,4)); --}}
$.ajax({
url : "/notes/createNotes",
type: "POST",
contentType: 'application/json',
data : JSON.stringify(submission.data)
}).done(function(response){
console.log(JSON.stringify(response, 4, null))
if(response.status === 'success'){
window.location.pathname = "/notes/getNotes"+response.data.id
}else{
window.location.pathname = "/notes/getNotes"
}
});
});
let cancelButton = document.getElementById("cancel")
cancelButton.onclick = function(){
window.location.pathname = "/notes/getNotes"
return false;
}
});
};
</script>
<div class="col g-ml-45 g-ml-0--lg g-pb-65--md">
{{#if flashMessage}}
<div class="noty_bar noty_type__info noty_theme__unify--v1 g-mb-25">
<div class="noty_body">
<div class="g-mr-20">
<div class="noty_body__icon">
<i class="hs-admin-info"></i>
</div>
</div>
<div>{{flashMessage}}</div>
</div>
</div>
{{/if}}
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 class="g-font-weight-300 g-font-size-28 g-color-black g-mb-28">Create Notes</h1>
<div class="g-brd-around g-brd-gray-light-v7 g-rounded-4 g-pa-15 g-pa-20--md g-mb-30">
<form id="pageForm" name="pageForm" action="/notes/getNotes" method="POST">
<div id="form"></div>
</form>
</div>
</div>
<div class="col-md-3"></div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment