sendgrid mail sending error upon placing multiple receiver - javascript

I'm using const sgMail = require('#sendgrid/mail'); and utilizing sendgrid version 7.6.2.
When I'm adding two email addresses in array and passing that into send() or sendMultiple() it's throwing me error like this.
status: 'failed',
> Error: Error: String expected for `email`
here's the section where I'm putting the multiple emails,
mailsTo = {
email: ["demo#email.com", "demo1#email.com"],
name: "demo",
type: 'to'
}
here if I pass one email as in form of string the mail is getting triggered. Can anyone please suggest what am I doing wrong.
Thanks in advance

According to the documentation the addresses are to be passed as an array of EmailData (string or object with email and name).
Please try the following:
mailsTo = [
{
email: "demo#email.com",
name: "demo"
},
{
email: "demo1#email.com",
name: "demo"
}
]
Assuming mailsTo is being pass as the to parameter for

Related

sending value of my textarea with graphql

I hope you all have a great day. I am coding my own personal website and I have a section called to contact me. The problem I have with this section is that I am trying to send my client email to my email and when I am trying to send their message to my server through Graphql I get this error
[
{
"message": "Syntax Error: Unterminated string.",
"locations": [
{
"line": 3,
"column": 123
}
]
}
]
the request I sent to my server is
'\n mutation{\n sendEmail(EmailInput: {name: "Test name", email: "Test#email.com",
subject: "this is test subject", message: "\n
this is the first line \nthis is the second line\nwhen I have multiple lines I have these problem\n
"}) {\n success\n message\n }\n }\n '
I don't know how to fix it I don't know why I get this error.
I used fetch to send my code backend :
const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}", message: "
${senderMessage.value}
"}) {
success
message
}
}
`;
const result = await fetch("http://localhost:2882/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: emailMutationQuery,
}),
});
const convertedResult = await result.json();
GraphQL supports variables, which can be used to supply input data separately from the query. The variables are just a separate JSON-encoded object. This avoids syntactic difficulties (and potential security risks!) from trying to embed the inputs directly in the query.
For this you'd write a fixed query, that declares and uses the variable, but doesn't depend on the per-request inputs
const emailMutationQuery = `
mutation SendEmail($emailInput: SendEmailInput!) {
sendEmail(EmailInput: $emailInput) {
success
message
}
}
`;
You'd then create a second object containing the variable(s). The top-level keys match what you declare in the GraphQL operation line, and their content matches the corresponding GraphQL input types.
const variables = {
emailInput: {
name: senderName.value,
email: senderEmail.value,
subject: senderSubject.value,
message: senderMessage.value
}
};
Note that this is an ordinary Javascript object, and we haven't quoted or escaped anything here.
Now when we make the request, we send the query and variables together
const result = await fetch("http://localhost:2882/graphql", {
...,
body: JSON.stringify({
query: emailMutationQuery,
variables: variables
})
});
Things like newlines in the message content will be escaped in the variables block, and get passed through correctly to the underlying GraphQL engine.
I actually find a solution for it but feel free to share your answers here. The solution I found for this problem was that you have to use JSON.stringify() for the textarea. you have to pass your textarea value to this function and js will take care of the rest. my code now looks like this
const emailMutationQuery = `
mutation{
sendEmail(EmailInput: {name: "${senderName.value}", email: "${senderEmail.value}", subject: "${senderSubject.value}",
message:${JSON.stringify(senderMessage.value)}}) {
success
message
}
}
`;
I hope this help you guys.

Validation to prevent brand names being in the email field?

So, I have this list of some brandnames:
const blackListedDomains = [
'facebook',
'google',
'amazon',
'netflix',
'hotmail',
'microsoft',
'gmail',
'yahoo',
]
which I need to prevent users to enter in the email field, what Schema could be built using Yup Package.
For example, I am trying this way:
const DomainSchema = Yup.object().shape({
subdomain: Yup.string()
.required('Required')
.lowercase()
.notOneOf(
blackListedDomains,
'Cannot use trademarked names in domain!',
),
})
But, I don't know how to get it from the email string, for example, if user inputs xyz#google.xyz, then how to extract google from the email string and then iterate it over the domain names list to find if it exists there and then show an error message ?
You can use test function of yup library to create a custom validation rule like this:
const DomainSchema = Yup.object().shape({
email: Yup.string()
.required("Required")
.lowercase()
.email("Not a valid mail")
.test(
"is-not-blacklist",
"Cannot use trademarked names in domain!",
(value) => {
if (value) {
const currentDomain = value.substring(
value.indexOf("#") + 1,
value.indexOf(".")
);
return !blackListedDomains.includes(currentDomain);
}
}
)
});
You can take a look at this sandbox for a live working example of this solution.

JS library to check if extra data field returned in http response payload?

I’m currently working on building end-to-end testing for an API another team is working on, and I was wondering if anyone perhaps knows about a JS library that I could use to test whether an extra field is returned in HTTP response body? The purpose of this functionality would be to keep the QA team informed when the dev team makes changes to the api via the tests, instead of the developers manually having to let us know they’ve created updates. I know this can be implemented manually but if the wheel already exists, I’d prefer to avoid recreating it lol.
Example scenario:
API call: GET user
- returns : user name, user ID and user birthday.
With proposed functionality, if the dev team made updates to the Get user call, and it returns the following
- return : user name, user ID, user birthday AND user address.
A test would fail to let me know that an extra field that wasn't expected (user address) was returned.
Schema validation seems to be what you are looking for. Besides the library mentioned in another answer, you may also want check a similar one: joi
const Joi = require('joi');
const schema = Joi.object().keys({
userName: Joi.string().alphanum().required(),
userId: Joi.number().required(),
userBirthDay: Joi.number().required(),
})
const result = Joi.validate({
userName: 'johndoe',
userId: 1234567,
userBirthDay: 1970,
userAddress: 'John Doe St.'
}, schema);
if (result.error) {
console.log(result.error.details);
}
In the spec you can make assertion on existence of error key in result object using the assertion library of your choice.
The example above assumes that you are using nodejs as an environment to run tests, but browser version of joi also exists: joi-browser
You need schema validation, there are libraries out there like ajv.
var ajv = new Ajv({ allErrors: true }); // options can be passed, e.g. {allErrors: true}
// API call: GET user - returns : user name, user ID and user birthday.
// With proposed functionality, if the dev team made updates to the Get user call, and it returns the following - return : user name, user ID, user birthday AND user address.
var schema = {
type: "object",
properties: {
userName: {
type: "string",
},
userId: {
type: "string",
},
userBirthdate: {
type: "string",
},
},
required: ["userName", "userId", "userBirthdate"],
additionalProperties: false,
};
var validate = ajv.compile(schema);
var validUser = {
userName: "John",
userId: "john",
userBirthdate: "01012000",
};
var invalidUser = {
userName: "John",
userId: "john",
userBirthdate: "01012000",
userAddress: "World",
};
var valid = validate(validUser);
console.log(`Valid user is valid: ${valid}`);
valid = validate(invalidUser);
console.log(`Invalid user is valid: ${valid}`);
console.log('Validate errors:', validate.errors);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.6.2/ajv.min.js"></script>

Underscore's findWhere and MongoDB object

I use MongoDB and I want to use Underscore.js in my Angular app.
I have a model "Email" with the fields: "subject", "body" and "id".
This Email object looks like this in the browser console:
$$hashKey
"005"
_id
Object { $oid="5478774a6a61734d8a000000"}
body
"Here is the sample conte...le ble ble. Nice email."
subject
"This is first template"
This is the controller code in Angular:
$scope.viewEmail = function(emailId) {
var email = _.findWhere(emailData.data.emails, { _id: emailId });
console.log(email);
};
So, I just want to find an email with the specific id - the id I want to get is saved in a local variable emailId.
I should do something like that: _id.$oid: emailId but it causes a syntax error in the javascript console: "missing : after property id".
This will do the job:
_.find(list, predicate, [context])
Here is a fiddle:
http://jsfiddle.net/bqegdy2t/
var emailData = {
data: {
emails: [
{ _id: { $oid: "someId" }, body: "Hello Every Body1" },
{ _id: { $oid: "someOtherId" }, body: "Hello Every Body2" },
]
}
};
var emailId = "someId";
var email = _.find(emailData.data.emails, function(email) {
return email._id.$oid === emailId;
});
console.log(email);
the difficulty lies in the mongo objectid format that is an unusual JSON object containing string.
try _id: emailId versus _id.$oid: emailId
another option: dot notation often needs quotes around it "_id.$oid" : emailId especially those with dollar signs

Using user-defined types in Cassandra with nodejs

I am trying to use user-defined types in Cassandra with nodejs.
Following the documentation, I successfully manage to do it in cqlsh (https://www.datastax.com/documentation/cql/3.1/cql/cql_using/cqlUseUDT.html). I manage to insert items in cqlsh but not ussing the cassandra-driver module.
I understand they are some intricacies do to the use of javascript (http://www.datastax.com/documentation/developer/nodejs-driver/1.0/nodejs-driver/reference/nodejs2Cql3Datatypes.html) and I have tried the different options offered but I couldnt not get it to work.
Here are my trials and their resulting error message:
var insertQuery = 'INSERT INTO mykeyspace.users (id, name) VALUES (?, ?)'
client.execute(insertQuery, ['62c36092-82a1-3a00-93r1-46196ee77204', { firstname: 'paul', lastname: 'jacques'}], {hints: ['uuid', 'map<text, text>']}, function(err) { console.log(err);})
{ name: 'ResponseError',
message: 'Not enough bytes to read 0th field java.nio.HeapByteBuffer[pos=0 lim=9 cap=9]',
info: 'Represents an error message from the server',
code: 8704,
query: 'INSERT INTO mykeyspace.users (id, name) VALUES (?, ?)' }
client.execute(insertQuery, ['62c36092-82a1-3a00-93r1-46196ee77204', { firstname: 'paul', lastname: 'jacques'}], { prepare: true }, function(err) { console.log(err);})
{ [TypeError: Not a valid blob, expected Buffer obtained { firstname: 'paul', lastname: 'jacques' }]
query: 'INSERT INTO mykeyspace.users (id, name) VALUES (?, ?)' }
Then what is the correct syntax to get it to work?
NB. I am using cassandra 2.1.1
The DataStax Node.js driver does not support User defined types yet, so the driver won't be able to serialize the data accordingly.
You can use json notation in CQL to access the individual fields. For example, queries like the following will work:
SELECT addr.street, addr.city FROM location WHERE id=?;
or
UPDATE SET addr['street'] = ?, addr['city'] = ? WHERE id = ?

Categories