Empty string handling in nodeJs or Javascript - javascript

I write below code for handling empty string and get the data
DB image
In this image we need to show data behalf of Program column. If Project column and Slug(from project) column have empty data then it will show Program's field 'CIL' and 'OSI'.
I was write below code
//this is database code
// file db.js
const findNews = async () =>
new Promise((resolve, reject) => {
const news = [];
if (!base) {
base = new Airtable().base(process.env.AIRTABLE_BASE);
}
base(tables.news)
.select({})
.eachPage(
(records, fetchNextPage) => {
records.forEach(record => {
const slugField = record.get('Slug (from Project)') || "";
news.push({
description: record.get('Description'),
date: record.get('Date') || "",
project: slugField[0] || "",
program: record.get('Program'),
link: record.get('External Link') || "",
});
});
fetchNextPage();
},
err => {
if (err) {
reject(new Error(err)); // Airtable returns an object here (vs an Error)
} else {
resolve(news);
}
}
);
});
Controllers code
async news(ctx) {
const { role, displayCatalog } = strapi.cache.users[ctx.state.user.email];
const allNews = strapi.cache.news.filter(fields => {
return (
(fields.program === null ||
fields.project === null ||
fields.link === null ||
fields.description === null ||
fields.date === null) &&
(fields !== null || fields !== undefined) &&
fields.program.includes(programFromRole(role))
);
});
const news = strapi.cache.news.filter(
neww => neww.program.includes(programFromRole(role)) && displayCatalog.includes(neww.project)
);
const newsData = news.concat(allNews);
return buildResponse(newsData);
},
This code runnable but in db.js file I used for sending empty string as "" but this approach is not good.
could you please help me out of problem?

Related

data list are not keeping the old elements when new ones are added

I've an upload list, the old data already in the list are removing from the list if I upload new data into the list. But I want to list all the data together. How can I fix this issue?
const [fileList, setFileList] = useState<AddedFile[]>([]);
const beginUpload = (file: File[]) => {
const addedFiles = file
?.filter((item) => item !== null)
.map((item): AddedFile => {
if (item === null) {
throw new Error('Item is null');
}
return {
title: item?.name || '',
fileName: item?.name || '',
};
});
setFileList([...addedFiles, ...fileList]);
file.forEach((item: File) => {
onUpload(item, {
title: item?.name || '',
fileName: item?.name || '',
}).catch((err) => {
console.error(err);
});
});
}
Update setFileList([...addedFiles, ...fileList]); to:
setFileList(currentList => {
return [...addedFiles, ...currentList]
});
Reference:
https://reactjs.org/docs/hooks-reference.html#usestate

Error in uploading marks Expected string but received array

I have a school management project, and in the "UploadMarks" tab, when I click on the button to send the form with the students attendance, the error "Error in uploading marks Expected string but received array", I've heard that it's a problem with lib validator for validations, but I canĀ“t resolve this error.
uploadMarks:
const Validator = require('validator');
const isEmpty = require('./is-empty');
const validateFacultyUploadMarks = (data) => {
let errors = {}
data.subjectCode = !isEmpty(data.subjectCode) ? data.subjectCode : '';
data.exam = !isEmpty(data.exam) ? data.exam : '';
data.totalMarks = !isEmpty(data.totalMarks) ? data.totalMarks : '';
if (Validator.isEmpty(data.subjectCode)) {
errors.subjectCode = 'Subject Code field is required';
}
if (Validator.isEmpty(data.exam)) {
errors.exam = 'Exam field is required';
}
if (Validator.isEmpty(data.totalMarks)) {
errors.totalMarks = 'Total marks field is required';
}
return {
errors,
isValid: isEmpty(errors)
};
}
module.exports = validateFacultyUploadMarks
teacherController:
uploadMarks: async (req, res, next) => {
try {
const { errors, isValid } = validateFacultyUploadMarks(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
const {exam, totalMarks, marks, department, year } = req.body
const isAlready = await Mark.find({ exam, department})
if (isAlready.length !== 0) {
errors.exam = "You have already uploaded marks of given exam"
return res.status(400).json(errors);
}
for (var i = 0; i < marks.length; i++) {
const newMarks = await new Mark({
student: marks[i]._id,
exam,
department,
marks: marks[i].value,
totalMarks
})
await newMarks.save()
}
res.status(200).json({message:"Marks uploaded successfully"})
}
catch (err) {
console.log("Error in uploading marks",err.message)
}
},
is-Empty:
const isEmpty = value =>
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0);
module.exports = isEmpty;

How to move the code to set ut DB and collection out from my file and just requre it?

So, let's say I have this code that works perfectly.
const {
Database
} = require("arangojs");
var db = new Database({
url: "http://localhost:8529"
});
const database_name = "cool_database";
db.useBasicAuth("username", "password123");
db.listDatabases()
.then(names => {
if (names.indexOf(database_name) > -1) {
db.useDatabase(database_name);
db.get();
} else {
db.createDatabase(database_name)
.then(() => {
db.useDatabase(database_name);
db.collection("my-collection").create();
});
}
});
const collection = db.collection("my-collection");
const getJobFromQueue = () => {
return db.query({
query: "FOR el IN ##collection FILTER DATE_TIMESTAMP(el.email.sendAfter) < DATE_NOW() AND el.status != 'processed' AND el.status != 'failed' SORT el.email.sendAfter LIMIT 1 RETURN el",
bindVars: {
"#collection": "my-collection"
}
})
.then(cursor => cursor.all());
}
But I want to move the top code out to another file and just require db and collection, how do I make that work? Have been struggling to make it work for too long now.
const {
db,
collection
} = require("./db");
const getJobFromQueue = () => {
return db.query({
query: "FOR el IN ##collection FILTER DATE_TIMESTAMP(el.email.sendAfter) < DATE_NOW() AND el.status != 'processed' AND el.status != 'failed' SORT el.email.sendAfter LIMIT 1 RETURN el",
bindVars: {
"#collection": "my-collection"
}
})
.then(cursor => cursor.all());
}
just do exactly what you proposed. move the upper part of your code to db.js and expose dband collection using exports:
db.js:
const {
Database
} = require("arangojs");
var db = new Database({
url: "http://localhost:8529"
});
const database_name = "cool_database";
db.useBasicAuth("username", "password123");
db.listDatabases()
.then(names => {
if (names.indexOf(database_name) > -1) {
db.useDatabase(database_name);
db.get();
} else {
db.createDatabase(database_name)
.then(() => {
db.useDatabase(database_name);
db.collection("my-collection").create();
});
}
});
exports.collection = db.collection("my-collection");
exports.db = db;
index.js:
const {
db,
collection
} = require("./db");
const getJobFromQueue = () => {
return db.query({
query: "FOR el IN ##collection FILTER DATE_TIMESTAMP(el.email.sendAfter) < DATE_NOW() AND el.status != 'processed' AND el.status != 'failed' SORT el.email.sendAfter LIMIT 1 RETURN el",
bindVars: {
"#collection": "my-collection"
}
})
.then(cursor => cursor.all());
}
WARNING:
keep in mind, there is a potential race condition in your code. you may end up using db and collection, before they hat been initialized.

Nodejs - Express - Best practice to handle optional query-string parameters in API

I want to make a API which have 5 optional query parameters, I want to know if there is a better way to handle this, right now I check each one of them with if conditions, which is kind of dirty! is there any way that I can handle all scenarios without using lot's of if conditions?
let songName = req.query.songName
let singerName = req.query.singerName
let albumName = req.query.albumName
let publishDate = req.query.publishDate
if(songName && singerName && albumName && publishDate) {
const response = songs.filter(c => {
return c.songName === songName && c.singerName === singerName && c.albumName === albumName && c.publishDate === publishDate
}
res.send({
"Data" : response
})
}
if(songName && singerName && albumName && !publishDate) {
const response = songs.filter(c => {
return c.songName === songName && c.singerName === singerName && c.albumName === albumName
}
res.send({
"Data" : response
})
}
if(songName && singerName && !albumName && publishDate) {
const response = songs.filter(c => {
return c.songName === songName && c.singerName === singerName && c.publishDate === publishDate
}
res.send({
"Data" : response
})
}
if(songName && !singerName && albumName && publishDate) {
const response = songs.filter(c => {
return c.songName === songName && c.albumName === albumName && c.publishDate === publishDate
}
res.send({
"Data" : response
})
}
if(!songName && singerName && albumName && publishDate) {
const response = songs.filter(c => {
return c.singerName === singerName && c.albumName === albumName && c.publishDate === publishDate
}
res.send({
"Data" : response
})
}
.
.
.
You could use the ternary operator to do this all in one query. If the parameter is defined you check for equality and else you just return true. This could look like this:
const response = songs.filter(c => {
return (songName ? (c.songName === songName) : true) &&
(singerName ? (c.singerName === singerName) : true) &&
(albumName ? (c.albumName === albumName) : true);
});
res.send({
"Data": response
})
I may find Lodash to be useful for this one:
const response = songs.filter(song => {
return _.isEqual(req.query, _.pick(song, Object.keys(req.query)))
})
I suggest you to use Joi
It is very powerful library for javascript validations. You can make even conditional validations using it. See the complete docs.
I created basic schema for your scenario here.
// validation
const schema = Joi.object().keys({
songName: Joi.string()
singerName: Joi.string()
albumName: Joi.string()
publishDate: Joi.date()
});
const { error, value } = Joi.validate(req.query, schema, { abortEarly: false, allowUnknown: false });
if (error !== null) return res.send(400, { code: 400, message: "validation error", error: error.details });
It is easier to read and understand for other developers too. You can standardized the validations in the overall project.

how to unit test and get the value of localStorage on react

I'm testing out logout function on our react app and I'm having trouble testing the localStorage. What I want to do is check if (value === 'logout') in my unit test so I can have a expect assertion that will check if localStorage has the item i'm testing for, this is where I'm having trouble. How can I assert that if (value === 'logout') then equals localStorage.removeItem('id_token')
Here is the .js snippet I'm testing for
_handleSelectItem = (event, value) => {
if (value === 'logout') {
const sharedLogic = () => {
localStorage.removeItem('id_token')
window.location = '/' // TODO: find a better way to reset the relay cache
}
const onSuccess = (response) => {
sharedLogic()
}
const onFailure = (transaction) => {
var error = transaction.getError() || new Error('Mutation failed.')
console.error(error)
sharedLogic()
}
this.props.relay.commitUpdate(
new SignOutUserMutation({
viewer: this.props.viewer
}
), {onSuccess, onFailure})
}
}
Here is the .spec.js I wrote that didn't quite do the job that I wanted
if(!global.localStorage) {global.localStorage = {} }
// if(value === 'logout')
describe('(Component) AccountManager | Logout ', () => {
let _component
let _props
let value = 'logout'
// if(value === 'logout')
beforeEach(() => {
_props = {
viewer: {
email: 'joe#example.com'
}
}
_component = shallowRenderWithProps(_props)
sinon.spy(global.localStorage, 'getItem')
sinon.spy(global.localStorage, 'setItem')
sinon.spy(global.localStorage, 'clear')
})
afterEach(() => {
global.localStorage.getItem.restore()
global.localStorage.setItem.restore()
global.localStorage.clear.restore()
})
it('Should check if Logout work correctly', () => {
if(value === 'logout');
console.log(global.localStorage)
expect(global.localStorage.getItem.withArgs('id_token').calledOnce).is.true;
})
Note the test above passes but does not clear the CodeCov error that indicated I should test this. I'm just getting started with react so I appreciate the helping me learn more
if if (typeof(Storage) !== "undefined" && localStorage.getItem(value) === 'logout') {
//[do your stuff here]
}

Categories