Testing graphql subscriptions with k6 - load-testing

Is it possible to test graphql subscriptions using k6 framework?
I tried to do it, but did not have much success. Also tried to do it with k6 websockets, but did not help.
Thanks

Grapqhql Subscription is based on Websockets so this is theoretically possible to implement using k6 WebSocket.
You can also refer to the documentation for subscriptions here.
You can also use the playground and Networks tab in developer tools to figure out the messages/requests that are sent to the server.
Here is how I was able to achieve it:
import ws from "k6/ws";
export default function(){
const url = "ws://localhost:4000/graphql" // replace with your url
const token = null; // replace with your auth token
const operation = `
subscription PostFeed {
postCreated {
author
comment
}
}` // replace with your subscription
const headers = {
"Sec-WebSocket-Protocol": "graphql-ws",
};
if (token != null) Object.assign(headers,{ Authorization: `Bearer ${token}`});
ws.connect(
url,
{
headers,
},
(socket) => {
socket.on("message", (msg) => {
const message = JSON.parse(msg);
if (message.type == "connection_ack")
console.log("Connection Established with WebSocket");
if (message.type == "data") console.log(`Message Received: ${message}`)
});
socket.on("open", () => {
socket.send(
JSON.stringify({
type: "connection_init",
payload: headers,
})
);
socket.send(
JSON.stringify({
type: "start",
payload: {
query: operation,
},
})
);
});
}
);
}
Hope this helps! 🍻

Related

Is there any solution for verifyPurchase in In-app-Purchase for ios flutter

I am implementing In-app purchases in my flutter app, there is the last step to verify the purchase by making a cloud function named to verify the purchase. I made a function and deployed it successfully to firebase but when I am testing this function in postman I got an error of bad request also when I use this function in the flutter app I got false each time.
Please help me do this accurately or recommend any tutorial/article.
I tried to implement cloud function in two ways. first one is here
import * as admin from "firebase-admin";
import * as Functions from "firebase-functions";
import {CLOUD_REGION,PURCHASE_TOKEN } from "./constants";
import fetch from 'node-fetch';
const functions = Functions.region(CLOUD_REGION);
admin.initializeApp();
export const verifyPurchase = functions.https.onCall(
async (
context,
): Promise<any> => {
const response = await fetch("https://buy.itunes.apple.com/verifyReceipt", {
method: 'POST',
body: JSON.stringify({
"receipt-data": PURCHASE_TOKEN,
"password": PURCHASE_PASSWORD
"exclude-old-transactions": true,
}),
headers: {
'Content-Type': 'application/json',
Accept: '/',
},
});
if(response.ok){
return response.body;
}else {
return response.error;
}
});
while test on postman getting this response
{
"result": {
"size": 0,
"timeout": 0
}
}

Twilio - Send email from function

Is there a way to send email from Twilio function? I understand that we can use sendgrid. I am looking a simpler solution.
Twilio evangelist here. 👋
As of now, you can use SendGrid from within a Twilio Function. The code below does the job for me and I just sent an email via a function
exports.handler = function(context, event, callback) {
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'sjudis#twilio.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg)
.then(() => {
callback(null, 'Email sent...');
})
.catch((e) => {
console.log(e);
})
};
The above email will most like end up in spam as test#example.com is not a very trust worthy email address. If you want to send emails from your own domains additional configuration is needed.
To run the code inside of the function, you have to make sure to install the sendgrid/mail mail dependency and provide the sendgrid token in the function configuration.
If you want to use this function to power e.g. messages you have to make sure that your return valid TwiML. :) When you create a new function you will get examples showing on how to do that.
Hope that helps. :)
Another way is to use the SendGrid API
const got = require('got');
exports.handler = function(context, event, callback) {
const requestBody = {
personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
from: { email: context.FROM_EMAIL_ADDRESS },
subject: `New SMS message from: ${event.From}`,
content: [
{
type: 'text/plain',
value: event.Body
}
]
};
got.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
};
};
Source: https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html

Microsoft Graph sendMail doesn't work and returns NULL

I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.

MS Graph Sample Application Integration Test not Working

I want to do what the MS Graph sample node app is doing in its integrationTests.js, but that test doesn't work. Here's what I've tried:
Followed the quick start for creating a node.js app.
Ran the app. Ensured it worked by sending an e-mail.
Modified the test Checking that the sample can send an email to use my account parameters.
Tried to run the test. It fails with 403: insufficient scope. The call to get the token returned scopes, but lacked Mail.Send.
In the post data for the call to login.microsoftonline.com, I added "scope: 'Mail.Send'"
I still receive a valid token, and the return scope includes Mail.Send, but when I try to post with that token, I get 400: cannot POST /beta/me/sendMail
I tried adding scope (Mail.Send) in the query string and as a header (thought I saw that somewhere), but it made no difference.
I added the Mail.Send permission (under "Application Permissions") for the app in the application registration portal.
I compared the token (using https://jwt.ms) from my test call to the call from the app when it works. I see no real difference. They both contain the Mail.Send scope.
Here is the code (which is only slightly different from what's in the sample):
// in graphHelper.js
function postSendMail(accessToken, message, callback) {
request
.post('https://graph.microsoft.com/beta/me/sendMail')
//.post('https://graph.microsoft.com/beta/me/sendMail?scope=Mail.Send') // nope
.send(message)
.set('Authorization', 'Bearer ' + accessToken)
.set('Content-Type', 'application/json')
.set('Content-Length', message.length)
.set('scope', 'Mail.Send') // nope
.end((err, res) => {
callback(err, res);
});
}
describe('Integration', function () { // mocha
var accessToken;
var scope;
const config = getConfig();
// My account variables in testConfig.json file
function getConfig() {
var configFilePath = path.join(__dirname, 'testConfig.json');
return JSON.parse(fs.readFileSync(configFilePath, { encoding: 'utf8' }));
}
function getAccessToken(done) {
var postData = querystring.stringify(
{
grant_type: 'password',
//grant_type: 'client_id', // not supported
//grant_type: 'authorization_code', // This assumes you've requested an auth code.
resource: 'https://graph.microsoft.com/',
scope: 'Mail.Send',
client_id: config.test_client_id_v2,
client_secret: config.test_client_secret_v2,
username: config.test_username,
password: config.test_password
}
);
var postOptions = {
host: 'login.microsoftonline.com',
port: 443,
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var postRequest = https.request(postOptions, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
const response = JSON.parse(data);
accessToken = response.access_token;
scope = response.scope;
done();
});
});
postRequest.on('error', function (e) {
console.log('Error: ' + e.message);
done(e);
});
postRequest.write(postData);
postRequest.end();
}
before( // eslint-disable-line no-undef
function (done) {
getAccessToken(done);
}
);
it('Checking that the sample can send an email',
function (done) {
var postBody = emailer.generateMailBody(config.test_name, config.test_username);
graphHelper.postSendMail(
accessToken, scope,
JSON.stringify(postBody),
function (error) {
assert(error === null, `The sample failed to send an email: ${error}`);
done();
});
}
);
});

Auto-generate swagger docs if you only use auto-discovery to discover DB tables

I am wondering if we can still auto-generate Swagger API documentation for our Loopback API server if we only use the auto-discovery features outlined here:
https://docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases
does anyone know if it's possible? If we use autodiscovery, I somehow doubt that any .json files for our models will get written to our server project, and that will make generating docs difficult.
Turns out yes it is possible, and the way to do that is to write the models-x.json files out for all models with a script, and then start the server after the script has finished!
https://docs.strongloop.com/display/public/LB/Database+discovery+API
this is standard practice for auto-discovery, here is my code that accomplishes this:
const loopback = require('loopback');
const fs = require('fs');
const path = require('path');
const async = require('async');
var ds = loopback.createDataSource('postgresql', {
'host': 'localhost',
'port': 5432,
'database': 'foo',
'username': 'bar',
'password': 'baz'
});
ds.discoverModelDefinitions(function (err, models) {
async.each(models, function (def, cb) {
ds.discoverSchema(def.name, null, function (err, schema) {
if (err) {
console.error(err.stack || err);
cb(err);
}
else {
fs.writeFile(path.resolve(__dirname, 'server/models', def.name + '.json'),
JSON.stringify(schema), {}, cb);
}
});
}, function (err) {
if (err) {
console.log(err.stack || err);
process.exit(1);
}
else {
console.log(' => Successfully wrote model data.');
process.exit(0);
}
});
});

Resources