JSON response: Node server and Sencha - node.js

I'm struggling to understand why I don't get anything in the Sencha view. I believe there is an issue with the json transferred between a server and the Sencha proxy. I have a server coded in node and express and a proxy reader in Sencha. But Sencha cannot read the data.
Server Side:
app.get('/weather/fulljson',function(req, res) {
var obj = {data: [{ from_user: 'world', data: 'inter' }, { from_user: 'world2', data: 'interw' }, { from_user: 'world3', data: 'interw' }]};
jsonP = false;
var cb = req.query.callback;
console.log(cb);
if (cb != null) {
jsonP = true;
res.writeHead(200, {
'Content-Type': 'text/javascript',
'connection' : 'close'
});
} else {
res.writeHead(200, {'Content-Type': "application/x-json"});
}
if (jsonP) {
res.end(cb + "(" + JSON.stringify(obj) + ");" );
}
else { res.end(JSON.stringify(obj));
}
)};
});
Sencha View:
Ext.define('Epic.view.Weather', {
xtype: 'graph',
extend: 'Ext.DataView',
//requires: ['Epic.store.SWeather'],
requires: ['Epic.model.MWeather', 'Ext.data.proxy.JsonP'],
config: {
store: {
autoLoad: true,
fields: ['from_user', 'data'],
proxy: {
type: 'jsonp',
url: 'http://localhost:3000/weather/fulljson',
reader: {
type: 'json',
rootProperty: 'data'
}
}
}
},
itemTpl: '{from_user}'
});
Response in Chrome:
Ext.data.JsonP.callback1({"data":[{"from_user":"world","data":"inter"},{"from_user":"world2","data":"interw"},{"from_user":"world3","data":"interw"}]});
But nothing appear in the view.

Did you check your store after load? is it contains data that you send? If yes - in that case something wrong with your view. You can use debugger tools and get your component and check store.
Also could you shows your model Epic.model.MWeather ? Actually if you have model, you don't have to add fields to your store.

Related

Apollo - How to add a dynamic header for subgraph

I am using the #apollo/gateway for a GraphQL implementation.
When implementing a subgraph, the endpoint is an internal DNS record. I have a total of 3 microservices, see below for the code snippet:
const { ApolloGateway, IntrospectAndCompose, RemoteGraphQLDataSource } = require("#apollo/gateway");
const gateway = new ApolloGateway({
supergraphSdl: new IntrospectAndCompose({
subgraphs: [
{ name: "users-api", url: `users.private/graphql?` },
{ name: "cars-api", url: `cars.private/graphql?` },
{ name: "posts-api", url: `posts.private/graphql?` }
],
}),
buildService({ name, url }) {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
Object.keys(context.headers || {}).forEach(key => {
if (context.headers[key]) {
request.http.headers.set(key, context.headers[key]);
}
});
},
});
},
});
What I am trying to do is sending a custom header to each of the subgraphs. For example:
subgraph users-api, inject header: service=users
subgraph cars-api, inject header: service=cars
Is this possible?
Thanks in advance!

InvalidClientQueryException when updating Document Library Metadata SPFx webpart

Need your help!
Am Uploading a document to the document library in SPFx webpart using REST API. I am not using PNP and React for file upload and updating metadata.
Post uploading the document, I am trying to update the metadata properties by getting the ID and updating the item.
File upload is done successfully. Able to get the ID of the Item added. While updating the metadata property - it is giving me Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"A type named 'SP.Data.SubmitxyzfileListItem' could not be resolved by the model. When a model is available, each type name must resolve to a valid type."}
Below is the code I am using
//Code for File Upload
private uploadFile(FinalName:string): Promise<any>{
try {
return new Promise((resolve) => {
var files = (<HTMLInputElement>document.getElementById('userFile')).files;
const spOpts: ISPHttpClientOptions = {
body: files[0]
};
var url=`${this.context.pageContext.web.absoluteUrl}${this.properties.primarylist}/_api/Web/Lists/getByTitle('${this.properties.fileuploadlist}')/RootFolder/Files/Add(url='${FinalName}', overwrite=true)`
const response = this.context.spHttpClient.post(url, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
response.json().then(async (responseJSON: any) => {
console.log("File Uploaded");
var uniqueGuid = await responseJSON.UniqueId;
this.updateDocLibMetadata(uniqueGuid);
console.log("uniqueGuid"+uniqueGuid);
resolve(uniqueGuid);
});
});
});
} catch (error) {
console.log("Error in uploadFile " + error);
}
}
\\Code for updating Document Library Metadata
private updateDocLibMetadata(uniqueGuid:string) {
var geturl=`${this.context.pageContext.web.absoluteUrl}${this.properties.primarylist}/_api/Web/Lists/getByTitle('${this.properties.fileuploadlist}')/GetItemByUniqueId(guid'${uniqueGuid}')?$select=id,name,UniqueId,Title,File/ServerRelativeUrl&$expand=File`;
this.context.spHttpClient.get(geturl,SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
response.json().then((responseJSON: any) => {
console.log("Id in updateDocLibMetadata :"+responseJSON["Id"]);
var itemId=responseJSON["Id"];
var posturl = this.context.pageContext.web.absoluteUrl +this.properties.primarylist+ `/_api/web/lists/GetByTitle('${this.properties.fileuploadlist}')/items(${itemId})`;
var payload = JSON.stringify({
"__metadata": {
'type': this.getListItemType(this.properties.fileuploadlist)
},
"Id_SubmitxyzQuestionId": this._requiredListProps.Id
});
var option = {
headers: {
'IF-MATCH': '*',
'Content-type': 'application/json;odata=verbose',
"accept": "application/json;odata=verbose",
"odata-version":"3.0",
'X-HTTP-Method': 'PATCH'
},
body: payload
};
//THIS FINAL CALL IS GIVING ERROR
return this.context.spHttpClient.post(posturl, SPHttpClient.configurations.v1, option).then((UpdateResponse: SPHttpClientResponse) => {
console.log(UpdateResponse.status + ':' + response.ok);
UpdateResponse.text().then(function (text) {
// do something with the text response
console.log("text:"+text);
});
})
.catch(reject => console.error('Error :', reject));
});
});
}
I did come through one post of PowerAutomate which says the solution was to check out the file then update the properties. Link to the PowerAutomate issue - https://powerusers.microsoft.com/t5/Building-Flows/Update-list-item-via-SharePoint-REST-API/m-p/534538#M69186
For SPFx webart also - would I have to use same approach ?
Any help is much appreciated.
Thanks.
Found answer to the above!
Changed the payload and the headers for the request and worked like a charm.
Changed to below code in updateDocLibMetadata method specified in the query.
var payload = JSON.stringify({
"Id_SubmitxyzQuestionId": this._requiredListProps.Id
});
var option = {
headers: {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=nometadata',
'odata-version': '',
'IF-MATCH': '*',
'X-HTTP-Method': 'MERGE'
},
body: payload
};

Why is my cookie not available in my handler function when testing?

I am using Hapi and this is my handler function:
function propertyDetailsValidateHandler(request, reply, source, error) {
console.log(request.state)
var data = joiValidationHelper.checkForErrors(request, error);
if (typeof data !== "undefined"){
return reply.view('property-details', data).code(400);
} else {
var details = request.state.details;
details.propertyType = request.payload.propertyType;
details.newBuild = request.payload.newBuild;
return reply.redirect('/property-details/postcode').state('details', details, {path: '/'});
}
}
And this is my test written using Jasmine:
describe('tell us about the property youre buying flow', function(){
it('test /property-details, status code and location', function(done){
var options = {
method: 'POST',
url: '/property-details',
headers: {
cookie: {details: { test: "test"}}
},
payload: {
propertyType: "freehold",
newBuild: true
}
};
server.inject(options, function(response){
detailsTestCookie = response.headers['set-cookie'][0].split(';')[0];
expect(response.statusCode).toBe(302);
expect(response.headers.location).toMatch("/property-details/postcode");
done();
});
});
})
The handler function runs correctly when I run my server and use the browser but when I run the test request.state is an empty object when I was expecting it to be the cookie I provided in the test hence my test fails as request.state.details is undefined. Is this the correct way to provide the headers with a cookie in my test?
This works in our project, using tape and Hapi.
var cookie = the_cookie_you_want_to_send;
Then in your test payload:
headers: { cookie: `details=${cookie}`}
The cookie needed to be encoded as that is how the cookie was registered in our server file:
server.state('details', {
ttl: null,
isSecure: false,
isHttpOnly: false,
encoding: 'base64json', //this is not encrypted just encoded
clearInvalid: false, // remove invalid cookies
strictHeader: false // don't allow violations of RFC 6265
});

How to update a document based on query using elasticsearch-js (or other means)?

I want to perform a update-by-query, specifically update a specific document that where field name that contains Gary. I am using the latest version of elasticsearch (2.3) I am using the official ES client for nodejs. Providing an alternative means to do this (find a document, update a specific field in the document) would be acceptable as a correct answer.
This has not yet been released in the JavaScript client. This will be available in the 2.3 API version of the Javascript client library. Right now, the JS client only supports up to apiVersion: 2.2
You can use any HTTP client (Postman, curl, /head/, Sense, ...) in order to hit the REST endpoint and carry out what you need.
If you do need to do this through Node.js, you can use the http module like this:
var http = require('http');
var options = {
host: 'localhost',
port: 9200,
path: '/your_index/your_type/_update_by_query',
method: 'POST'
};
var req = http.request(options, function(resp){
resp.on('data', function(chunk){
// check update response
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
var query = {
"script": {
"inline": "ctx._source.field = 'value2'"
},
"query": {
"term": {
"field": "value1"
}
}
};
// write data to request body
req.write(JSON.stringify(query));
req.write('\n');
req.end();
I did similar, may helpful for others
async function updateBranches(req){
try{
let query = '';
for (const key in req) {
if (Object.hasOwnProperty.call(req, key)) {
query = `${query}ctx._source["${key}"] = "${req[key]}";`
}
}
const res = await esclient.updateByQuery({
index: branchesIndex,
refresh: true,
body: {
query: {
match: {
branchKey: req.branchKey
}
},
script: {
lang: 'painless',
source: query
},
}
})
return res;
} catch(e){
console.log(e,'error');
}}

Refresh_token using oauth.io

Hi I am student of Computer Science and doing some experiments on oauth.io. but i am facing problem to get refresh_token after getting code successfully. After getting the code i am writing the follwing line of code but its giving me Internal server error..
The code is
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: result.code,
key: '5WeOrrR3tP6RyShR1',
secret: '2_q3tb_D_qgDwSGpt' },
success: function (data) {
console.log("result", data);
}
});
Which url used to get refresh_token? please someone help me.
thanks
there was a bug recently in the js sdk when you set the response type server-side (to get the code & refresh_token), so you may have to redownload oauth.js if you use a static version.
I guess your jquery code is server side (because of the nodejs tag and the use of a code), but i had an error "no transport" that i fixed with a new XMLHttpRequest. Here is my full test:
var jsdom = require('jsdom').jsdom;
var win = jsdom().createWindow();
var $ = require('jquery')(win);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function () {
return new XMLHttpRequest;
}
$.ajax("https://oauth.io/auth/access_token", {
type: "post",
data: {
code: process.argv[2],
key: 'xxxxxxxxxxxx',
secret: 'yyyyyyyyyyyy' },
success: function (data) {
console.log("result", data);
},
error: function() {
console.error(arguments);
}
});
and my result looks like:
{ access_token: 'xxxxxxxxxxx',
request:
{ url: '{{instance_url}}',
required: [ 'instance_url' ],
headers: { Authorization: 'Bearer {{token}}' } },
refresh_token: 'yyyyyyyyyyyyy',
id: 'https://login.salesforce.com/id/00Db0000000ZbGGEA0/005b0000000SSGXAA4',
instance_url: 'https://eu2.salesforce.com',
signature: 'zzzzzzzzzzzzz',
state: 'random_string',
provider: 'salesforce' }

Resources