Skip to content

Commit

Permalink
updated auth,article controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucky-victory committed Apr 14, 2022
1 parent f12f33f commit e3ccd2b
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 38 deletions.
7 changes: 4 additions & 3 deletions constants/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@



const {Sqler}=require('harpee');
const {query}=new Sqler().select(["a.id","a.publishedAt","a.intro","a.title","a.heroImage","a.slug","a.category","a.readTime","a.modifiedAt","a.authorId","a.views","a.content","u.fullname as _fullname","u.id as _id","u.twitter as _twitter","u.linkedIn as _linkedIn","u.username as _username","u.profileImage as _profileImage","u.bio as _bio"]).from("BlogSchema","Articles").as("a").innerJoin("BlogSchema","Users").as("u").on("a","authorId").isEqual("u","id").where("a.published=true")
const IS_PROD=process.env.NODE_ENV==='production';
const IS_DEV=process.env.NODE_ENV !=='production';
const ARTICLES_SQL_QUERY=`SELECT a.id,a.publishedAt,a.intro,a.title,a.authorId,a.content,a.views,a.heroImage,a.slug,a.tags,a.category,a.readTime,a.modifiedAt,u.fullname as _fullname,u.id as _id,u.twitter as _twitter,u.linkedIn as _linkedin,u.bio as _bio,u.username as _username,u.profileImage as _profileImage FROM BlogSchema.Articles as a INNER JOIN BlogSchema.Users as u ON a.authorId=u.id WHERE a.published=true `;
const ARTICLES_SQL_QUERY=query;
// const ARTICLES_SQL_QUERY=`SELECT a.id,a.publishedAt,a.intro,a.title,a.authorId,a.content,a.views,a.heroImage,a.slug,a.tags,a.category,a.readTime,a.modifiedAt,u.fullname as _fullname,u.id as _id,u.twitter as _twitter,u.linkedIn as _linkedin,u.bio as _bio,u.username as _username,u.profileImage as _profileImage FROM BlogSchema.Articles as a INNER JOIN BlogSchema.Users as u ON a.authorId=u.id WHERE a.published=true `;
module.exports={
IS_PROD,
IS_DEV,
Expand Down
6 changes: 3 additions & 3 deletions controllers/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ const {title,publishedAt,modifiedAt,slug,heroImage,id,authorId,category,views,re
let {content,intro}=article;
content=decode(content);
intro=decode(intro);
let {fullname,twitter,linkedIn,profileImage,username,bio}=await Users.findOne({"id":authorId});
bio=decode(bio);
let author=await Users.findOne({"id":authorId},["fullname","twitter","linkedIn","id","username","profileImage","bio"]);
author['bio']=decode(author['bio']);
// get tag ids from ArticleTags table where article id matches
const tagIds=await ArticleTags.query(`SELECT tagId FROM BlogSchema.ArticleTags WHERE postId='${id}'`);

Expand All @@ -52,7 +52,7 @@ comments=ArrayBinder(comments,replies,{

const newViewsCount=parseInt(views)+1 || 1;
await Articles.update([{id,'views':newViewsCount}]);
res.status(200).json({title,content,slug,views,publishedAt,modifiedAt,intro,heroImage,id,category,author:{'id':authorId,fullname,twitter,linkedIn,profileImage,bio,username,readTime, tags},comments});
res.status(200).json({title,content,slug,views,publishedAt,modifiedAt,intro,heroImage,id,category,author,readTime, tags,comments});

}
catch(err){
Expand Down
41 changes: 25 additions & 16 deletions controllers/articles.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const Comments=require('../models/comments');
const Replies=require('../models/replies');

const asyncHandler=require('express-async-handler');
const {Nester,ArrayBinder,GenerateSlug,CalculateReadTime, StringToArray, NullOrUndefined, NotNullOrUndefined, isEmpty, ObjectArrayToStringArray, AddPropsToObject, StringArrayToObjectArray,MergeArrays,GetIdOfDuplicateTags,RemoveDuplicateTags}=require("../helpers/utils");
const {Nester,ArrayBinder,GenerateSlug,CalculateReadTime, StringToArray, NullOrUndefined, NotNullOrUndefined, isEmpty, ObjectArrayToStringArray, AddPropsToObject, StringArrayToObjectArray,MergeArrays,GetIdOfDuplicateTags,RemoveDuplicateTags, GetLocalTime}=require("../helpers/utils");
const {Converter}=require("showdown");
const converter=new Converter();
const {encode,decode}=require("html-entities");
Expand Down Expand Up @@ -41,8 +41,8 @@ const articlesId=articles.map((article)=>article.id);
articles=articles.map((article)=>{
article.title=decode(article.title);
article.content=decode(article.content);
article.intro=decode(article.intro);
article.author.bio=decode(article.author.bio);
!NullOrUndefined(article.intro) ? article.intro=decode(article.intro) : '';
!NullOrUndefined(article.author && article.author.bio) ? article.author.bio=decode(article.author.bio) : '';
return article;
});

Expand Down Expand Up @@ -96,29 +96,38 @@ content= converter.makeHtml(content);
content=encode(content);
intro=converter.makeHtml(intro);
intro=encode(intro);
const currentDate=new Date().toISOString();
const currentDate=GetLocalTime();
const createdAt=currentDate;
const slug= GenerateSlug(title);
const authorId=req.userId;
const totalWords= String(NotNullOrUndefined(title) + NotNullOrUndefined(content)) ||'';
const {readTime}=CalculateReadTime(totalWords)
const publishedAt=published? createdAt : null;
const newArticle= {createdAt,publishedAt,title,content,heroImage,slug,category,authorId,published,modifiedAt:createdAt,views:0,readTime,intro};
const {readTime}=CalculateReadTime(totalWords)
const publishedAt=published? createdAt : null;
const newArticle= {createdAt,publishedAt,title,content,heroImage,slug,category,authorId,published,modifiedAt:createdAt,views:0,readTime,intro};

// try getting tags from database to see if they exist
const tagsExist=await Tags
tags=StringArrayToObjectArray(tags);
tags=AddPropsToObject(tags,{createdAt});
const {inserted_hashes:insertedArticleId}=await Articles.create(newArticle);
let {inserted_hashes:insertedTagsId}=await Tags.createMany(tags);
insertedTagsId=StringArrayToObjectArray(insertedTagsId,'tagId');
const tagIdsWithArticleId=AddPropsToObject(insertedTagsId,{postId:insertedArticleId[0],createdAt})
await ArticleTags.createMany(tagIdsWithArticleId)
const tagsExist=await Tags.find({getAttributes:["id","text"],where:`text IN("${tags.join('","')}")`});
let remainingTags=tags;
let duplicateTagsId;
if(tagsExist.length){
duplicateTagsId=GetIdOfDuplicateTags(tagsExist,tags);
remainingTags=RemoveDuplicateTags(tagsExist,tags);
}
let tagsAsObj=StringArrayToObjectArray(remainingTags);
tagsAsObj=AddPropsToObject(tagsAsObj,{createdAt});

const {inserted_hashes:insertedArticleId}=await Articles.create(newArticle);
let {inserted_hashes:insertedTagsId}=await Tags.createMany(tagsAsObj);
let mergedTagIds=MergeArrays(insertedTagsId,duplicateTagsId);
mergedTagIds=StringArrayToObjectArray(mergedTagIds,'tagId');
const tagIdsWithArticleId=AddPropsToObject(mergedTagIds,{postId:insertedArticleId[0],createdAt})
await ArticleTags.createMany(tagIdsWithArticleId)

res.status(201).json({status:201,message:"article successfully created","article":{id:insertedArticleId[0],...newArticle}})
}
catch(error){
const status=error.status ||500;
res.status(status).json({message:"an error occurred, couldn't creaded new article",error,status})
res.status(status).json({message:"an error occurred, couldn't create new article",error,status})

}
});
Expand Down
8 changes: 4 additions & 4 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use strict";
const Users=require("../models/users");
const bcrypt=require("bcrypt");
const { GenerateUsername, RemoveKeysFromObj, NullOrUndefined, isEmpty}=require("../helpers/utils");
const { GenerateUsername, RemoveKeysFromObj, NullOrUndefined, isEmpty, GetLocalTime, GenerateUserID}=require("../helpers/utils");
const asyncHandler=require("express-async-handler");
const { encode } = require("html-entities");
const {Converter}= require("showdown");
Expand Down Expand Up @@ -38,8 +38,8 @@ const usernameExist= await Users.findOne({username});
if(usernameExist){
return res.status(400).json({message:`'${username}' have been taken`});
}
const joinedAt=new Date().toISOString();
const newUser= {profileImage,bio,twitter,linkedIn,joinedAt,username,fullname,email,superUser:false,github};
const joinedAt=GetLocalTime();
const newUser= {id:GenerateUserID(), profileImage,bio,twitter,linkedIn,joinedAt,username,fullname,email,superUser:false,github};

// hash the password before storing in database
try{
Expand Down Expand Up @@ -77,7 +77,7 @@ try{
}
const passwordMatch= await bcrypt.compare(String(password),user.password);

if(user && !passwordMatch){
if(!passwordMatch){
return res.status(400).json({message:"invalid credentials",status:400});

}
Expand Down
11 changes: 9 additions & 2 deletions helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ const Utils = {
* @returns {(string | number)[] | []}
**/
GetIdOfDuplicateTags(prevTags, newTags) {
if(!Array.isArray(prevTags) && !Array.isArray(newTags)){
if(Array.isArray(prevTags) && Array.isArray(newTags)){

const duplicateTagsIds = [];
for (let i = 0; i < prevTags.length; i++) {
Expand All @@ -225,7 +225,7 @@ const Utils = {
* @returns {string[] | []}
**/
RemoveDuplicateTags(prevTags, newTags) {
if(!Array.isArray(prevTags) && !Array.isArray(newTags)){
if(Array.isArray(prevTags) && Array.isArray(newTags)){
let nonDuplicateTags = [];
const keysLeft = []
for (let i = 0; i < prevTags.length; i++) {
Expand All @@ -247,6 +247,13 @@ MergeArrays(arr=[], arr2=[]) {
const newArr = [];
newArr.push(...arr, ...arr2)
return newArr
},
GetLocalTime(){
const timeZoneOffsetInHours=(new Date().getTimezoneOffset() / 60);
const currentHour=new Date().getHours();
const localDateTimeInMilliseconds=new Date().setHours(currentHour - timeZoneOffsetInHours);
const localTime=new Date(localDateTimeInMilliseconds).toISOString();
return localTime;
}
}

Expand Down
2 changes: 0 additions & 2 deletions models/articles.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ const {Schema,Model}=require("harpee");
const BlogSchema=new Schema({name:"BlogSchema",fields:{
title:String,
content:String,
tags:String,
createdAt:Date,
publishedAt:Date,
modifiedAt:Date,
authorId:String,
category:String,
slug:String,
tagId:String,
views:Number,
readTime:Number,
heroImage:String,
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"dotenv": "^16.0.0",
"express": "^4.17.2",
"express-async-handler": "^1.2.0",
"harpee": "^3.0.9",
"harpee": "^3.0.12",
"html-entities": "^2.3.2",
"http-errors": "^2.0.0",
"jsonwebtoken": "^8.5.1",
Expand Down

0 comments on commit e3ccd2b

Please sign in to comment.