I am new to Ember and is trying to create a small application using version beta 2.3.0.
Provided a country and zipcode, I am trying to get the city and zipcode.
With Mirage and a custom serializer (I am using the same format as of real json) my code works perfectly.
However, with the real API, the Promise remains in Pending state. There is no error in console.
And the logs in my serializer does not display when using real service indicating that the serializer is not executing.
Has anyone faced a similar issue before. Please help.
In my controller, I am finding the record as:
this.store.find('address', zipcode).then(
function(address) {
console.log("Hello Got Address");
});
My adapters/application.js :
export default DS.RESTAdapter.extend({
host: 'http://real_url_here',
pathForType: function(type) {
return '';
}});
The JSONAPISerialier is overriden in serializers/application.js as:
export default DS.JSONAPISerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
.......... // Code goes here
}});
In my mirage/config.js, I am returning sample json for 2 zipcodes and at the end I have added:
this.passthrough('http://real_url_here/**');
to invoke real service for other zipcodes
I got the answer finally :).
I had to disable the mirage in development :
To disable in development,
// config/environment.js
...
if (environment === 'development') {
ENV['ember-cli-mirage'] = {
enabled: false
}}
Related
I have read multiple answers to these kind of issues, and each answer has its own response;
In my case I am not getting any of those as my interfaces simply don't map the json like I want it to. I have tried multiple solutions, since working with Root-object and nested interfaces, but here I am, asking which is the best approach to deal with these kind of JSON objects in the front end, how to map it this particular one (a fork-Join). and I wanted to ask what are the real benefits of using the interfaces/classes/ maps besides the Intellisense? It has to do with data propagation?
The json structure in question:
{
Title: "",
Year: "",
Rated: "",
Released: "",
Runtime: "",
…}
Simple as it is. But back in my service I call it with a forkjoin:
getMovies(name: string, year?: string): Observable<any> {
let shortPlot = this.http.get(
"https://www.omdbapi.com/?t=" +
name +
"&plot=short&y=" +
year +
"&apikey=[my key]"
);
let fullPlot = this.http.get(
"https://www.omdbapi.com/?t=" + name + "&plot=full&apikey=[my key]"
);
return forkJoin([shortPlot, fullPlot]);
}
The subscription in the component:
getMovie() {
this.spinner = true;
this.movieService
.getMovies(this.name.value)
.subscribe((dataList: any) => {
this.movies = Array.of(dataList[0]);
this.spinner = false;
let error: any = this.movies.map(error => error.Error);
if (error[0]) {
this.notfound = error[0];
this.error = true;
} else {
this.error = false;
this.movieRate = this.movies.map(rating => rating.imdbRating.toString());
}
})),
error => console.log(error);
}
And in the HTML I render the data like this:
<div *ngFor="let m of movies">
<h5 class="mt-0">{{m.Title}}, {{m.Year}}</h5>
</div>
So as you can see I am not working with an interface and I should. Anyone can sort me out?
Thank you
EDIT: the log after subscribe:
let's break it down,
what are the real benefits of using the interfaces/classes/ maps besides the Intellisense?
Using interfaces and classes will not just give you intellisense but will also provide static type safety for your code. Why this is important, let's say you have a interface with following structure,
export interface Demo {
field: string;
}
// in some other file 1
demo.field.substring(1, 2);
// in some other file 2
demo.field.lenght;
You are using this interface in many places in your code. Now, for some reason you get to know that the property should be number not string. So here typescript will give you all the errors at compile time only.
export interface Demo {
field: number;
}
// in some other file 1
demo.field.substring(1, 2); // error
// in some other file 2
demo.field.lenght // error
Also, after typescript transpiles it will generate javascript files, now as javascript is interpreted language, your code will not be tested until the javascript run-time actually executes the problematic line, but in typescript you will get errors in compilation stage only.
You can get away with using any everywhere, but with that you will be missing the static typings.
With interfaces and classes, you also get OOP features, such as inheritance etc.
It has to do with data propagation?
Your frond-end is never aware what type of data will be received from api. So it's developers responsibility that the received data should be mapped to some interface.
Again as mentioned above, if somehow back-end changes type of some field in received json, then it will again be caught in compile time.
In case of forkJoin which combines output of two jsons you can have two different types.
Demo
export interface Demo1 {
field1: string;
}
export interface Demo2 {
field2: number;
}
// in service layer
getData(): Observable<[Demo1, Demo2]> {
const res1 = this.http.get(...);
const res2 = this.http.get(...);
return forkJoin([res1, res2]);
}
// in component
this.dataService.getData().subscribe(res => {
// you will get type safety and intellisense for res here
console.log(res[0].field1)
})
I am not working with an interface and I should.
Yes, you should use interfaces, if you are not using using features of typescript then whats the point using it. :)
I posted this last week and have made progress since, where I've discovered the packages that VSCode's JSON support is delivered via extensions:
https://github.com/vscode-langservers/vscode-json-languageserver
https://github.com/Microsoft/vscode-json-languageservice
and all the rest. I'm trying to reuse this in an Electron (NodeJS) app. I'm able to fork a process starting the language server and initialize it:
lspProcess = child_process.fork("node_modules/vscode-json-languageserver/out/jsonServerMain.js", [ "--node-ipc" ]);
function initialize() {
send("initialize", {
rootPath: process.cwd(),
processId: process.pid,
capabilities: {
textDocument: true
}
});
}
lspProcess.on('message', function (json) {
console.log(json);
});
and I see that console.log firing and showing it seems to be up correctly.
My thoughts are that I just want to send a textDocument/didChange event as per the LSP:
send('textDocument/didChange', {
textDocument: TextDocument.create('foo://bar/file.json', 'json', 0, JSON.stringify(data))
});
where data is a JSON object representing a file.
When I send that message and other attempts at it I get
error: {code: -32601, message: "Unhandled method textDocument/didChange"}
id: 2
jsonrpc: "2.0"
Any idea what I'm doing wrong here? My main goal is to allow edits through my Electron app and then send the updated JSON to the language server to get schema validation done.
EDIT: I'm even seeing unhandled method initialized when I implement connection.onInitialized() in the jsonServerMain.js.
EDIT2: Update, I figured out where I was going wrong with some of this. initialized and textDocument/didChange are notifications, not requests.
EDIT2: Update, I figured out where I was going wrong with some of this. According to the LSP, initialized and textDocument/didChange are notifications, not requests. Requests have an id field that notifications don't, so when sending a notification, remove the ID field.
I am trying to send a JSON payload to a ASP.NET MVC action that has a JsonResult. When I debug the action I am finding that the JSON data does not seem to be coming through. I have tried both letting the MVC do the deserialization to a custom object parameter and accepting a string parameter that I would then deserialize within the method. In both cases the parameter is coming in null. Below are both the MVC action signature and the node code I'm using to call the action.
Action signature
[HttpPost]
public JsonResult MyAction(MyCustomClass parm)
Node code
var httpntlm = require('httpntlm');
var requestStructure = {
sfId: '000000000000000',
emails:[{
Id: '2',
Label: 'asdfesed',
EmailAddress: 'me#mydomain.com'
}]
}
httpntlm.post({
url: "http://localhost:63102/MyController/MyAction",
username: 'me',
password: 'pwd',
workstation: 'choose.something',
domain: '',
json: requestStructure
}, function (error, response) {
console.log('error ' + error)
console.log('status ' + response.statusCode)
console.log('body ' + response.body)
});
I really haven't found any examples of using httpntlm for a POST. I'm sure I'm missing something but can't seem to figure out what. If there is a site that has good documentation for this please point me in that direction.
The problem was in the service and not the caller. The service was a pseudo Web API action off of a MVC controller. I put the method in a separate ApiController and the values showed up.
I've been banging my head against deserializing data with Ember. I feel like I've set it up right but I keep getting the same error. I'm trying to use the EmbeddedRecords Mixin, but it simply hasn't worked for me. Below is my debug data.
DEBUG: Ember : 1.6.1
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery : 1.10.2
DEBUG: Model Fragments : 0.2.2
Here is a simple setup of what I've been doing. I have my model defined like this -
App.Subject = DS.Model.extend({
title: DS.attr('string'),
sections: DS.hasMany('section')
});
App.Section = DS.Model.extend({
title: DS.attr('string'),
subject: DS.belongsTo('subject')
});
App.SubjectSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
sections: { embedded: 'always' }
}
});
and here is the format of the JSON payload I'm sending for a 'show'
{
"subject": {
"_id":"549987b098909eef0ac2d691",
"title":"Maths",
"sections":[{
"title":"Precalc",
"_id":"549987b098909eef0ac2d693"
}, {
"title":"Calc",
"_id":"549987b098909eef0ac2d692"
}],"__v":0
}
}
I get the errors in the console
Error while processing route: subjects.show undefined is not a function TypeError: undefined is not a function
at Ember.Mixin.create.extractSingle (http://localhost:3300/js/highered.js:2043:25)
at apply (http://localhost:3300/js/highered.js:20664:27)
at superWrapper [as extractSingle] (http://localhost:3300/js/highered.js:20240:15)
at Ember.Object.extend.extractFind (http://localhost:3300/js/highered.js:4007:21)
at Ember.Object.extend.extract (http://localhost:3300/js/highered.js:3892:37)
at http://localhost:3300/js/highered.js:11864:34
at invokeCallback (http://localhost:3300/js/highered.js:23228:19)
at publish (http://localhost:3300/js/highered.js:22898:9)
at publishFulfillment (http://localhost:3300/js/highered.js:23318:7)
at http://localhost:3300/js/highered.js:28736:9
highered.js:16581 undefined is not a function TypeError: undefined is not a function
at Ember.Mixin.create.extractSingle (http://localhost:3300/js/highered.js:2043:25)
at apply (http://localhost:3300/js/highered.js:20664:27)
at superWrapper [as extractSingle] (http://localhost:3300/js/highered.js:20240:15)
at Ember.Object.extend.extractFind (http://localhost:3300/js/highered.js:4007:21)
at Ember.Object.extend.extract (http://localhost:3300/js/highered.js:3892:37)
at http://localhost:3300/js/highered.js:11864:34
at invokeCallback (http://localhost:3300/js/highered.js:23228:19)
at publish (http://localhost:3300/js/highered.js:22898:9)
at publishFulfillment (http://localhost:3300/js/highered.js:23318:7)
at http://localhost:3300/js/highered.js:28736:9
Which as best I can tell is directly related to extractSingle at the this.keyForAttribute method
extractSingle: function(store, primaryType, payload, recordId, requestType) {
var root = this.keyForAttribute(primaryType.typeKey),
partial = payload[root];
updatePayloadWithEmbedded(store, this, primaryType, partial, payload);
return this._super(store, primaryType, payload, recordId, requestType);
},
although an interesting thing to note is that the error occurs at extractArray when I am using the subjects index route, which return the json above but with array brackets as well.
extractArray: function(store, type, payload) {
var root = this.keyForAttribute(type.typeKey),
partials = payload[pluralize(root)];
forEach(partials, function(partial) {
updatePayloadWithEmbedded(store, this, type, partial, payload);
}, this);
return this._super(store, type, payload);
}
Which makes me think that Ember Data is having trouble recognizing the format. This happens any time I define a serializer for a model, not just when I enable embedded records.
I'm hoping someone will be able to explain this. As a final note I've been using the Ember Data Model Fragments library as well, but I disabled that and still got this error so I don't think that is it.
The Embedded Records mixin doesn't work with the RESTSerializer before beta 9.
You can view the state of it here Ember-data embedded records current state?
You'll also want to be wary of updating ember or ember data without the other version in certain circumstances. Ember Data cannot read property 'async' of undefined
I'm currently working a Neo4j REST API wrapper for nodejs (node-neo4j).
Just making it ready for v2.0 of Neo4j
My fork: https://github.com/Stofkn/node-neo4j of https://github.com/philippkueng/node-neo4j
Is it possible to use the REST API to create a node with an integer like:
{ name: 'Kristof', age: 77 }
It creates a Node like this { name: 'Kristof', age: '77' }
Is the only workaround a Cypher query or a server plugin?
It should create the node with an numeric property, if it doesn't it's a bug but the code for that has been around for a long while.
For 2.0 I'd suggest to focus on the transactional endpoint first and add support for the REST API later on :)
Thanks for your help Michael.
I had to remove the type 'form' otherwise the integer is interpreted as a string.
My solution for a simple node creation without labels:
var request = require('superagent');
request
.post(this.url + '/db/data/node')
.send(node)
// .type('form') remove this line
.set('Accept', 'application/json')
.end(function(result){
if(typeof result.body !== 'undefined')
that.addNodeId(result.body, callback);
else
callback(new Error('Response is empty'), null);
});