CLIENT_FETCH_ERROR while using getSession inside apollo context - session

I was building an applicaiton using Next-Auth in the frontend and Apollo server at the backend.
This is my backend Code :
const server = new ApolloServer({
schema,
csrfPrevention: true,
cache: 'bounded',
context: async ({ req, res }) => {
const session = await getSession({ req })
return { session }
},
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
],
});
I'm getting this error :
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error fetch is not defined {
error: {
message: 'fetch is not defined',
stack: 'ReferenceError: fetch is not defined\n' +
' at _callee$ (/Users/adi/Desktop/chat/backend/node_modules/next-auth/client/_utils.js:52:13)\n' +
' at tryCatch (/Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/regeneratorRuntime.js:72:17)\n' +
' at Generator._invoke (/Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/regeneratorRuntime.js:55:24)\n' +
' at Generator.next (/Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/regeneratorRuntime.js:97:21)\n' +
' at asyncGeneratorStep (/Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/asyncToGenerator.js:3:24)\n' +
' at _next (/Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/asyncToGenerator.js:22:9)\n' +
' at /Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/asyncToGenerator.js:27:7\n' +
' at new Promise (<anonymous>)\n' +
' at /Users/adi/Desktop/chat/backend/node_modules/#babel/runtime/helpers/asyncToGenerator.js:19:12\n' +
' at _fetchData (/Users/adi/Desktop/chat/backend/node_modules/next-auth/client/_utils.js:88:21)',
name: 'ReferenceError'
},
url: 'http://localhost:3000/api/auth/session',
message: 'fetch is not defined'
}
I have NEXTAUTH_URL= http://localhost:3000 in my .env.
What am I missing ?

Related

How to return a value from Cypress custom command

I am polling task for async rest call, how do I return value of taskStatus from this Cypress custom function. I want to use this value in my spec file. Is this the right way?
**Cypress.Commands.add("pollTask", (TASK_URI,token) => {
// const regex = /Ok|Error|Warning/mg;
var taskStatus =''
cy.log(" *Task_URI : " + TASK_URI)
cy.log(" *X-Auth-token : " + token)
cy.server()
var NEWURL = Cypress.config().baseUrl + TASK_URI
cy.request({
method: 'GET',
url: NEWURL,
failOnStatusCode: false,
headers: {
'x-auth-token': token
}
}).as('fetchTaskDetails')
cy.log("local: " + token)
cy.get('#fetchTaskDetails').then(function (response) {
taskStatus = response.body.task.status
cy.log('task status: ' + taskStatus)
expect(taskStatus).to.match(regex)
})
return taskStatus
})**
You must return a Promise. Here's a simple get/set example from Cypress Custom Commands documentation.
In your case, you can return taskStatus like this:
Cypress.Commands.add("pollTask", (TASK_URI,token) => {
const regex = /Ok|Error|Warning/mg;
// var taskStatus =''
cy.log(" *Task_URI : " + TASK_URI)
cy.log(" *X-Auth-token : " + token)
// cy.server() --server() is not required with cy.request()
var NEWURL = Cypress.config().baseUrl + TASK_URI
cy.request({
method: 'GET',
url: NEWURL,
failOnStatusCode: false,
headers: {
'x-auth-token': token
}
}).as('fetchTaskDetails');
cy.log("local: " + token);
cy.get('#fetchTaskDetails').then(function (response) {
const taskStatus = response.body.task.status;
cy.log('task status: ' + taskStatus);
expect(taskStatus).to.match(regex);
cy.wrap(taskStatus); // --this is a promise
});
// return taskStatus --not a promise
})
You will be able to get taskStatus in your test using then():
cy.pollTask(TASK_URI, token).then(taskStatus => {
// do something with taskStatus
});

How do I get the message using Office.js in a react add-in

I am building a new react Outlook add-in and need to be able to download the current email.
The Office.js API has the getFileAsync method off the Office.context.document object but not the Office.context.mailbox.item object.
also as a requirement this needs to work in both Office online and local installs of Outlook.
In the existing com add-in I had direct access to the mail item.
Here is the code that I currently have to call into the API, but this only retrieves metadata.
/*
https://learn.microsoft.com/en-us/outlook/add-ins/use-rest-api#get-the-item-id
*/
public getMessageViaRest = () => {
const context: Office.AsyncContextOptions & { isRest: boolean } = {
isRest: true
};
Office.context.mailbox.getCallbackTokenAsync(context, (tokenResults) => {
if (tokenResults.status === Office.AsyncResultStatus.Failed) {
this.setState({ error: 'Failed to get rest api auth token' });
return;
}
const apiId: string = Office.context.mailbox.convertToRestId(Office.context.mailbox.item.itemId, 'v2.0');
const apiUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + apiId;
try {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + tokenResults.value
})
}).then((response) => {
response.json().then((body) => {
for (const key in body) {
this.state.details.push({ name: key, value: JSON.stringify(body[key]) });
}
this.forceUpdate();
});
});
} catch (error) {
this.setState({ error: JSON.stringify(error) });
}
});
}
Its not perfect but the REST Api does have an end point that will return the file's EML contents.
public downloadViaRest = () => {
const context: Office.AsyncContextOptions & { isRest: boolean } = {
isRest: true
};
Office.context.mailbox.getCallbackTokenAsync(context, (tokenResults) => {
if (tokenResults.status === Office.AsyncResultStatus.Failed) {
this.setState({ error: 'Failed to get rest api auth token' });
return;
}
const apiId: string = Office.context.mailbox.convertToRestId(Office.context.mailbox.item.itemId, 'v2.0');
const apiUrl = Office.context.mailbox.restUrl + '/v2.0/me/messages/' + apiId + '/$value';
try {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + tokenResults.value
})
}).then((response) => {
response.blob().then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'Message.eml';
a.click();
});
});
} catch (error) {
}
});
}

Openvidu server API REST with fetch

I start up KMS+OPENVIDU server with docker. Everything works nice with web component when i use JQ ajax:
For example (this works fine):
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: response => resolve(response.data.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
}
})
If i put fetch (native javascript) :
var myPromise = fetch(this.ovServerUrl + '/api/sessions', {
method: 'POST',
// mode: 'cors',
// credentials: 'same-origin',
// redirect: 'follow',
body: JSON.stringify(
{ customSessionId: sessionId }
),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + this.ovSecret)
}
})
return myPromise.then(response => {
console.log('return resolve !response', response)
console.log('return resolve !response.data.id! ', response.data.id)
return response.id
})
I got response but without response.id .
Looks like :
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://MY_DOMAIN:4443/api/sessions"
Any suggestion ?

WIX API response

I have the following function in my WIX website, which is making a request to an external API:
export function current_pull(page, per_page, filter_mode, view_id) {
const url_request = URL + page + '&per_page=' + per_page + '&filtermode=' + filter_mode + '&view_id=' + view_id;
return fetch(url_request, {
method: 'get',
headers: {
'X-AUTH-TOKEN': API_KEY,
'X-SUBDOMAIN': SUBDOMAIN
},
}).then(function(response) {
if (response.status >= 200 && response.status < 300) {
console.log("current answered");
var items = response.json();
console.log(items);
} else {
console.log("there was an error" + response.statusText);
}
})
.catch( (err) => {
console.log(err);
});
}
The console.log(items); outputs:
Promise {
_c: [],
_a: undefined,
_s: 0,
_d: false,
_v: undefined,
_h: 0,
_n: false }
How do I get the actual API response
response.json() is also a Promise so in this case you need to change your code as follows:
response.json().then(items => console.log(items))
You may check further documentation here: Body.json()

Register an AWS GIT code push event in Exact Online ERP

When a developer checks in code through a GIT push to AWS codecommit, I want to register an event in our ERP package Exact Online. This allows a project manager to review from within the ERP package the commits.
AWS Codecommit only supports triggers through SNS and Lambda; there is no hookup for batch files or so. I've been playing around with AWS Lambda and managed to post an event from AWS Codecommit to Slack, but to Exact Online it seems harder.
How can I post the GIT event of code commit to a business object in Exact Online?
The best way is to use a combination of AWS Lambda and Invantive Data Access Point, using a script such as:
console.log('Loading function codecommit2slack.');
const aws = require('aws-sdk');
const codecommit = new aws.CodeCommit({ apiVersion: '2015-04-13', region: 'eu-west-1' });
const querystring = require('querystring');
const https = require('https');
const url = require('url');
//
// To get the slack hook url, go into slack admin and create a new "Incoming Webhook" integration.
//
const slack_url = 'https://hooks.slack.com/services/SECRET/STUFF';
const slack_req_opts = url.parse(slack_url);
slack_req_opts.method = 'POST';
slack_req_opts.headers = {'Content-Type': 'application/json'};
exports.handler = function(event, context)
{
console.log('Run codecommit2slack.');
(event.Records || []).forEach(function (rec)
{
var details = rec.codecommit.references[0];
var commitId = details.commit;
var ref = details.ref;
var repository = rec.eventSourceARN.split(":")[5];
console.log("Repo " + repository + ", commit ID " + commitId + " on " + ref);
var params =
{ commitId: commitId
, repositoryName: repository
};
codecommit.getCommit
( params
, function(err, data)
{
if (err) console.log(err, err.stack); // an error occurred
else
{
var commitMessage = data.commit.message;
var authorName = data.commit.author.name;
var committerName = data.commit.committer.name;
console.log(commitMessage);
var postData = querystring.stringify
(
{ 'connection': 'PUBLIC\\Exact Online (nl)'
, 'format': 'Xml'
, 'query': "insert into events(description, enddate, notes, startdate, status) values ('" + repository + ": " + commitMessage.replace(/[^\x20-\x7E]/gmi, "") + "', sysdate, '" + committerName + " / " + commitId + "', sysdate, 50)"
}
)
;
var daphttpoptions =
{ host: "data-access-point.com"
, port: 443
, path: '/eol/stable/dap/Results'
, auth: 'EXACT-ONLINE-USER' + ":" + 'EXACT-ONLINE-PASSWORD'
, method: 'POST'
, headers:
{ 'Content-Type': 'application/x-www-form-urlencoded'
, 'Content-Length': Buffer.byteLength(postData)
}
}
var dapreq = https.request
( daphttpoptions
, function (res)
{
if (res.statusCode === 200)
{
console.log('posted to DAP');
context.succeed('posted to DAP');
}
else
{
console.log('post to DAP failed with status code: ' + res.statusCode);
context.fail('status code: ' + res.statusCode);
}
}
);
dapreq.on
( 'error'
, function(e)
{
console.log('problem with DAP request: ' + e.message);
context.fail(e.message);
}
);
//
// Send to Data Access Point.
//
dapreq.write(postData);
dapreq.end();
var req = https.request
( slack_req_opts
, function (res)
{
if (res.statusCode === 200)
{
console.log('posted to slack');
context.succeed('posted to slack');
}
else
{
console.log('post to slack failed with status code: ' + res.statusCode);
context.fail('status code: ' + res.statusCode);
}
}
);
req.on
( 'error'
, function(e)
{
console.log('problem with Slack request: ' + e.message);
context.fail(e.message);
}
);
//
// Send to development-audit channel.
//
req.write(JSON.stringify({username: committerName, as_user: true, text: commitMessage + " on " + repository + " (ID: " + commitId + ", ref " + ref + ")", channel: '#development-audit'}));
req.end();
}
}
);
});
};
console.log('Finished loading function codecommit2slack.');
This script also includes a post to Slack. First version of code based upon https://gist.github.com/vgeshel/1dba698aed9e8b39a464, thx.
The result in Exact Online will look something like this, but ofcourse you can also use it to create for instance an article or a Serial Number for each new commit or tag:

Resources