how to use sequelize specific errors? - node.js

How do you import sequelize errors?
I want to use specific errors like SequelizeUniqueConstraintError) for error handling.
try {
query...
} catch(e){
if (e instanceof SequelizeUniqueConstraintError) {
next(new ResourceError(e.toString(), 401))
} else {
next(new ResourceError(e.toString(), 500))
}
}
I'm getting SequelizeUniqueConstraintError is not defined, but I can't seem to navigate through the sequelize instance to find any error classes?

Check the source code of SequelizeUniqueConstraintError. The class named UniqueConstraintError. The SequelizeUniqueConstraintError is the value of name property. It's NOT a JavaScript class. So you should use UniqueConstraintError.
E.g.
import { UniqueConstraintError } from 'sequelize';
try {
throw new UniqueConstraintError({ message: 'test unique constraint' });
} catch (e) {
if (e instanceof UniqueConstraintError) {
console.log(401);
} else {
console.log(500);
}
}
The execution result:
401
package version: "sequelize": "^5.21.3"

Related

firebase-admin: FieldValue.arrayUnion not working NodeJS

I'm using firebase-admin v11.2.1
I can update a title in a project using:
if (title) {
batch.update(projectRef, {
title
})
}
But I cannot add an item to an array using:
batch.update(projectRef, {
admins: admin.firestore.FieldValue.arrayUnion(`/users/${admin}`)
})
The error is being caught in a catch block, but the error comes back as an empty object
} catch (err) {
res.status(500).json({ error: err })
}
resolves as:
{
"error": {}
}
Everything I read doing what I want to do point to arrayUnion as the answer, but it's not working for me. Any help is appreciated - thank you.
Edit: Here is the way a project is modeled.
I'm on another codebase too where arrayUnion is NOT working. I get the error:
const ids = members.map((member) => member.id);
await projectRef.update({
members: admin.firestore.FieldValue.arrayUnion(...ids)
)}
error TypeError: Cannot read properties of undefined (reading 'arrayUnion')
Though I'm in another codebase where arrayUnion is working exactly like you'd expect (firebase-admin version 9.8):
if (role === 'admin') {
batch.update(organisationRef, {
invitedAdmins: admin.firestore.FieldValue.arrayUnion(userId)
})
}
So very stumped 🤔
const { FieldValue } = require('firebase-admin/firestore');
FieldValue.arrayUnion(userId)

NestJS with TypeORM - Catch PostgreSQL unique_violation error on save()

I have got a function in a service that needs to get a value of a new or already existing object from the database and save it.
Issue is that name attribute of this object needs to be unique.
I know i can just create a .some() function over all database objects to check if i can enter this new value but its probably very unoptimal.
I would like to create somethign like this (below) but i have no idea what to do next:
const newObject = await this.repository
.save({
...newObjectDto,
})
.catch(err => {
if (err instanceof QueryFailedError) {
// some code for err checking to make
// sure i only catch the unique_violation
// error and then throw error
}
});
Error code for unique_violation is 23505. You can check out the full list of error codes returned by PostgreSQL here.
In order to catch a unique constraint violation, you can do:
try {
const newObject = await this.repository
.save({
...newObjectDto,
})
}
catch(err) {
if (err instanceof QueryFailedError) {
if(err.code === '23505') {
console.log(`Unique constraint ${err.constraint} failed`);
throw err;
}
}
}

Unable to locate element error in selenium webdriver node.js

I have put an if else condition in selenium webdriver node.js to check if a string contains an "Add New" string, but I am getting the error Unable to locate element: // *[contains(text(),'Add New')]
Here is the code:
if (driver.findElement(By.xpath("// *[contains(text(),'Add New')]"))) {
reject(new Error("This is an error"));
} else {
resolve(true);
}
Try this one
string bodyText = driver.findElement(By.xpath("//body")).text;
if (bodyText.Contains('Add New')) {
reject(new Error("This is an error"));
} else {
resolve(true);
}
Or
try {
driver.findElement(By.xpath("// *[contains(text(),'Add New')]"));
reject(new Error("This is an error"));
}
catch (ElementNotFound e) {
resolve(true);
}
Note: the first one should be significantly faster, since the second approach would try to wait for implicit wait amount of time before it throws the error for the element not being found.

How to check if a document contains a property in Cloud Firestore?

I want to know if there is a way to check if a property is present in a Cloud Firestore document. Something like document.contains("property_name") or if there is a document property exist.
To solve this, you can simply check the DocumentSnapshot object for nullity like this:
var yourRef = db.collection('yourCollection').doc('yourDocument');
var getDoc = yourRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
if(doc.get('yourPropertyName') != null) {
console.log('Document data:', doc.data());
} else {
console.log('yourPropertyName does not exist!');
}
}
})
.catch(err => {
console.log('Error getting document', err);
});
You could use the in operator like in the snippet bellow
const ref = admin.firestore().collection('yourCollectionName').doc('yourDocName')
try {
const res = await ref.get()
const data = res.data()
if (!res.exists) {
if (!("yourPropertyName" in data)) {
// Do your thing
}
} else {
// Do your other thing
}
} catch (err) {
res.send({err: 'Something went terribly wrong'})
}
I think you refer to making a query.
Still there is no way to check if some field is present or not in the Firestore. But you can add another field with value true/false
val query = refUsersCollection
.whereEqualTo("hasLocation", true)
query.get().addOnSuccessListener {
// use the result
}
check out this links for more
https://firebase.google.com/docs/firestore/query-data/queries
How do I get documents where a specific field exists/does not exists in Firebase Cloud Firestore?

Node.js and mongoose (mongodb) error cannot read property '' of null

I have a findOne query, and when ever i verify if it returned a empty document i get thrown a error saying 'cannot read property 'username' of null'. That happend when i try to acess doc.username in if(!doc.username) {
My code:
function checkAccDb(username, password) { console.log(2);
/* Check if accounts exists in db */
db.findOne({username: username}, function(err, doc){ console.log(3);
if(err) throw err;
if(!doc.username) {
add2stack(username, password);
}
else if(doc.status == 200) {
end(username, password, 1000);
}
else if(doc.status == 401) {
if(doc.password == password)
end(username, password, 401);
else
add2stack(username, password);
}
else {
add2stack(username, password);
}
});
}
Could anyone please explain me what's happening here?
Thanks!
The query succeeds but doesn't find any matches, so both err and doc are null. You need to check if doc is null and handle that case appropriately.
A typical implementation would be like this
db.findOne({username: username},function(err, doc) {
if (err) {
// handle error
}
if(doc != null)
{
if(!doc.username)
{
//handle case
}
else
{
//handle case
}
}
});
To get the solution check following things.
1. Check model name which you have defined or the name of the folder where all your models are present must be right because in my case in models folder where i have defined all my models i was using different model name so as there was no model named that, thats'y i was getting the error.
2. Check Schema name or folder name where it is located.

Resources