I'm currently testing a graphQL query string, however when I run the test, it fails. I'm not sure why the escape character is getting added to my expected value, any thoughts?
const expected = `{"query": "mutation {
anonymousConsentSet(
input: {\"name\":\"John Doe\",\"address\":\"123 Main St\",\"phoneNumber\":\"123456677\",\"emailAddress\":\"test#test.com\"}
)
}", "variables": ""}`;
const mockFormData = {
firstName: 'John',
lastName: 'Doe',
phone: '123456677',
address: '123 Main St',
email: 'test#test.com'
};
it('should get expected query', () => {
const output: any = createQuery(mockFormData);
expect(output).toBe(expected); // <------------This is failing because of unmatched escape characters
});
Notice the expected variable does not contain escape characters, so why is it showing after running the test below?
Try casting both of them to .toString() . I had the same problem, but only when I used .toContain it showed me that I was actually comparing 2 different types.
Related
I´m using typescript on node js to extracta data from Excel and save it on mongodb, there is however a field that has an id hardcoded, but when I try to save it as an ObjectId, I get the error:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
On this site I´ve seen several posts, and... the string doesnt have empty spaces and yes, I have imported the library
import { Types } from 'mongoose';
institucion: Types.ObjectId('5fe0c8dc7d8f144e8532252'),
The Schema, none of them work:
institucion: {type: Schema.Types.ObjectId},
institucion: {type: Object},
Saving it:
const guardarEmpresario = async (data: any, idEmpresa:any) => {
data.negocio.push(idEmpresa);
//console.log('data.negocio ', data.negocio);
var datoDelEmpresario: any = [];
datoDelEmpresario.push({
nombre: data.nombre,
institucion: Types.ObjectId(data.institucion),
correoElectronico: data.correoElectronico,
telefono: data.telefono,
negocio: data.negocio
});
const empresarios = mongoose.model('Empresarios', EmpresariosSchema, 'Empresarios');
return await empresarios.create(datoDelEmpresario);
After a while, I found that the id that my boss gave me was 1 character short.
I am trying to use the "or" operator in Joi ver.17.4.0
As you can see, in the code below, I want either or both of the attributes/properties to be allowed, but not neither.
The problem is that Joi does not allow a string to be empty. So, to have it empty, I need to:
Joi.string().allow('')
This makes it not empty according to the "or" operator. So I can not get the 'name' to be empty in the eyes of "or".
It won't validate properly.
It validates even when I do this (but it shouldn't):
validatePerson(createPerson(''));
Keep in mind that I'm actually validating POST input on a node express API, so this is some simplified code to illustrate the issue:
const Joi = require('Joi');
function createPerson(name, age) {
const person = { name: name, age: age };
console.log(person);
return person;
}
function validatePerson(person) {
const schema = Joi.object({
name: Joi.string().allow(''),
age: Joi.number(),
}).or("name", "age");
console.log(schema.validate(person));
return schema.validate(person);
}
validatePerson(createPerson('')); // This should fail validation but doesn't
validatePerson(createPerson()); // Should fail and does
validatePerson(createPerson('Bob')); // Should pass and does
validatePerson(createPerson('', 7)); // Should pass and does
validatePerson(createPerson('Bob', 7)); // Should pass and does
As far as I understand, you want to allow the name to be empty an string, only if the age exists.
To acheive that, you can use .when:
name: Joi.string().when('age', { is: Joi.exist(), then: Joi.allow('') })
This way, your first example will fail as you expected.
I am trying to associate a list of contacts to a customer using the associations setter method, however, it always throws the error 'invalid input syntax for integer: "[object Object]"'.
The relevant query mentioned in the error is: UPDATE "contactperson" SET "refCustomerId"=$1,"updatedAt"=$2 WHERE "id" IN ('[object Object]')
This is how I use the setter:
db.customer.findByPk(customerID, {
include: [{
model: db.address,
as: 'address',
},{
model: db.contactoption,
as: 'contactOptions',
}, {
model: db.contactperson,
as: 'contactPersons',
}]
}).then(customer => {
customer.setContactPersons([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]);
});
This is the association:
Customer.hasMany(models.contactperson, {
foreignKey: 'refCustomerId',
as: 'contactPersons'
});
Any idea what I'm doing wrong?
I managed to resolve this issue using the following code:
db.contactperson.bulkCreate([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]).then(newContactPersons => {
customer.setContactPersons(newContactPersons);
});
It's a more complicated approach than intended, but it get's the job done.
You used set<ModelName>s that just updates a link field of given records. If you need to create contactperson record you need to use createContactPerson instead of setContactPersons (NOTE: you cannot create several records at once).
customer.createContactPerson({
firstName: 'tester',
lastName: 'tester',
description: 'lorem ipsum'
});
compare to:
const contactPerson = db.contactperson.findById(1);
if (contactPerson) {
customer.addContactPersons([contactPerson.id]);
}
set<ModelName>s - replaces old linked records with the new existing ones
add<ModelName>s - adds exisiting records in addition to old ones
create<ModelName> - create a new non-existing record in addition to old ones
See hasMany special methods
Exactly what Anatoly posted.
I had method declared on TypeScript like:
declare addPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;
When i changed to:
declare createPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;
Everything works so remember - how you describe name of method its very necesary.
I have a query that returns an array, with Object.key (array) .foreach I am iterating, I want to know the value of a property in specific array.
Example:
Object.keys(arreglo).forEach(function(key) {
console.log(arreglo[key]);
});
The output is:
name: "Pepito",
Surname: "Perez"
I want to know how to get only the value of the surname
I know it will not work but it would be something like:
console.log(arreglo[key].surname);
You can use Array.forEach on the original array as shown below. You can even extract the fields you are interested using Array.map.
// let's assume the arrary you got from your query is in this format
const arreglo = [
{ firstname: "fn1", surname: "ln1"},
{ firstname: "fn2", surname: "ln2"},
{ firstname: "fn3", surname: "ln3"}
];
// you can log `surname` for each entry in the array
arreglo.forEach(v => console.log(v.surname));
// you can use map to transform the array to just have `surname` using array.map()
const surnames = arreglo.map(v => v.surname);
console.log(surnames);
Is this what you are looking for
const object1 = {
a: {firstname:"sali",lastname:"mali"},
b: {firstname:"sali",lastname:"mali"},
c: {firstname:"sali",lastname:"mali"}
};
Object.keys(object1).forEach(function(key){console.log(object1[key].lastname)});
I using nodejs v4 with sequelize, and I have a model like this:
var Device = sequelize.define('Device', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true
},
tenantId: {
type: DataTypes.BIGINT,
allowNull: false
},
token: {
type: DataTypes.STRING,
allowNull: false
}
}, {
tableName: 'devices'
});
When I select a device by id the type of id is a string, exemple:
Device.findById(9).then( function(result) {
console.log(result.toJSON().id + 10);
});
The output will be 910, rather than 19, so I look at json and a saw this:
{
id: "9"
tenantId: "123"
token: "adsadsdsa"
}
The id in found device is a string, but I defined it as a number...
Doesn't it should be { "id": 9 } ?
How can I select a device with the types that I defined previously?
BIGINT maximum value is 2^63-1, javascript can safely represent up to 2^53. To be on the safe side libraries return those numbers as strings.
If you want to have numbers instead of strings, you can use this library https://github.com/mirek/node-pg-safe-numbers which deals with this issue.
I found a fix to this problem on sequelize repo.
https://github.com/sequelize/sequelize/issues/4523
The pg module used for sequelize returns bigint as string because bigints are not guaranteed to fit into js numbers. So I change my model to use integer (DataTypes.INTEGER)
IMO, a smoother solution is to force parsing of int to int, instead of strings. Checkout this issue and comments.
Trying to put this line before your logic code worked for me, this forces parsing of int8 to int, instead of strings:
require("pg").defaults.parseInt8 = true;
...
try {
const list = await Posts.findAll();
console.log(JSON.stringify(list));
} catch (e) {
console.log(e.message);
}
By default, sequelize try format your results. You can set raw :true for get raw data