retrieving data using Ember - json

as I go deeper into EmberJS, I got into this context where I need to use HTTP request. As a start, I tried to retrieve JSON data so I made a test page that returns JSON and I also verified that it is in JSON by deserializing it. No errors were encountered but there is no output at all. Below are the details of my code
application.js
App = Ember.Application.create({});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://172.19.20.30/EmberTest/testApi.aspx'
});
event.js
App.Event = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string')
});
router.js
App.Router.map(function () {
this.resource('events', {path: '/'});
});
App.EventsRouter = Ember.Route.extend({
model: function () {
return App.Event.find();
}
});
JSON output from host
{ "events": [{ "id": 1, "title": "test title", "body": "test body" },{ "id": 2, "title": "another title", "body": "another body" }] }
HTML
<script type="text/x-handlebars" data-template-name="events">
this is an example
{{#each e in model}}
<label>{{e.title}}</label><br />
{{/each}}
</script>
what could possibly be missing in my code? comments, opinions, suggestions are greatly appreciated

Looks like the return JSON is wrong.. it should be singular:
{ "event": [{ "id": 1, "title": "test title", "body": "test body" },{ "id": 2, "title": "another title", "body": "another body" }] }
When you do a find with Ember Data it should have the model name:
this.store.find('event') So Ember-data know where the return map to.
This will generate a URL http://host:port/event
If you are changing host it should just be the base URL you are changing and not absolute. So in your case:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://172.19.20.30/EmberTest'
});
Then the URL will become http://172.19.20.30/EmberTest/events

Related

Cypress login to REST endpoint is unauthorized, Postman works - upload of JSON file

We have a REST service with an incoming REST endpoint that accepts data. It has no web interface (Swagger or so), only the API. With Postman I can POST a JSON file (response code is 202) to it and then read the uploaded data from another endpoint.
When I want to log in to the same endpoint with Cypress to upload a JSON file from the fixtures folder (with the same body as in the Postman request), then I get response code 401 instead – Unauthorized. I have the feeling that the cypress request is wrong because the logfile of the service does not write a message when I use the cypress POST but it does when I use the Postman POST.
First question: What could I be doing wrong in the cypress request?
Second question: Once the authentication works, how can I POST/upload/push the content of the JSON file to that endpoint? Because I have no webpage to interact with, I cannot use click button functions. The documentation mainly deals with interpreting a JSON response but not with sending it.
My cypress code:
it('logs in to connector through REST API', () => {
cy.request({
method: 'POST',
url: 'localhost:8095/connector/demands/v1/demandData',
failOnStatusCode:false,
form: true,
body: {
Username: 'user',
Password: 'pass',
}
})
})
import my-request from '../fixtures/my-request.json'
it('loads the JSON file', () => {
cy.fixture('my-request.json')
})
The structure of the JSON file to upload is not too simple, here is a shortened version:
{
"#metadata": {
"context": "{{A}}"
},
"pool": "{{B}}",
"action": "NEW",
"Type": "ANNOUNCEMENT",
"ON": "Order123",
"PON": "PO123",
"SNN": "SN123",
"direction": "OUT",
"mode": 3,
"pack": [
{
"out": {
"outKey": "OUT14",
"outQuantity": "3",
"dimension": {
"length": "303",
"width": "33",
"height": "903",
"unit": "mm"
},
"layers": "3",
"weight": "3000",
"weightUnit": "grm",
"in": [
{
"inKey": "IN12",
"inQuantity": "3",
"article": {
"articleKey": "article3",
"quantity": "300",
"PON": "Art_PO300",
"SNN": "Art_SN300"
}
}
]
},
"p1": "pack3",
"p2": "pack4",
"store": true
},
{
"out": {
"outKey": "OUT23",
"outQuantity": "5",
"dimension": {
"length": "505",
"width": "55",
"height": "905",
"unit": "mm"
},
"layers": "5",
"weight": "5000",
"weightUnit": "grm",
"in": [
{
"inKey": "IN19",
"inQuantity": "5",
"article": {
"articleKey": "article5",
"quantity": "500",
"PON": "Art_PO500",
"SNN": "Art_SN500"
}
}
]
},
"p1": "pack5",
"p2": "pack5",
"store": true
}
]
}
Solution found. "form: true" must not be given because this overrides the content-type.
You can pass the contents of the fixture file(which is json) in the request body like this:
describe('Some Test Suite', function() {
// we can use these values to log in
const username = 'jane.lane'
const password = 'password123'
it('logs in to connector through REST API', () => {
cy.fixture('my-request.json').then(myFixture => {
cy.request({
method: 'POST',
url: 'localhost:8095/connector/demands/v1/demandData',
auth: {
username,
password,
},
failOnStatusCode: false,
form: true,
body: myFixture
})
})
})
})
For HTTP auth you have to use. You can check out this cypress recipe.
auth: {
username,
password,
}

InlineQueryResultArticle of answerInlineQuery in Telegram Bot API with Google Apps Script

I'm using google apps script for Telegram Bot API & I'm having problem with InlineQueryResultArticle in answerInlineQuery method.
function answerInlineQuery(iqid, result){
var data = {
method: "post",
payload: {
method: "answerInlineQuery",
inline_query_id: iqid,
results:JSON.stringify(result)
}
}
}
Here is the format of result :-
var result= {
InlineQueryResultArticle:[
{type:'article',id: iqid, title:"RESULT 1", input_message_content:"TEXT 1"},
{type:'article',id: iqid, title:"RESULT 2", input_message_content:"TEXT 2"}
]
};
answerInlineQuery(iqid, result);
I have turned on Inline Mode in #BotFather. My bot is also receiving inline queries and for every request I can see my inline query id properly & I can also see the result receiving as [object Object].
But, the problem is I'm not getting any results.
REF: In answerinlinequery, the results should be a JSON-serialized array of results for the inline query using any of these results.
Can anyone point out where am I going wrong ?
The id field for a InlineQueryResultArticle must be unique for each result. However you are setting the id as iqid for both results.
You should replace them with custom ids.
var result= {
InlineQueryResultArticle:[
{type:'article',id: "1", title:"RESULT 1", input_message_content:"TEXT 1"},
{type:'article',id: "2", title:"RESULT 2", input_message_content:"TEXT 2"}
]
};
After many attempts I found solution:
Here there are an inline answer with three results
****Be careful :change value of document_file_id with a sample file_id from your bot else you will see an error
//your bot token placed here
const token = "";
tgmsg('answerInlineQuery', {
"inline_query_id": update['inline_query']['id'],
"results": JSON.stringify([
//inline result of an article with thumbnail photo
{
"type": "article",
"id": "1",
"title": "chek inline keybord ",
"description": "test ",
"caption": "caption",
"input_message_content": {
"message_text": "you can share inline keyboard to other chat"
},
"thumb_url": "https://avatars2.githubusercontent.com/u/10547598?v=3&s=88"
},
//inline result of an article with inline keyboard
{
id: "nchfjdfgd",
title: 'title',
description: "description",
type: 'article',
input_message_content: {
message_text: "inline is enabled input_message_content: {message_text: message_text}message_text"
},
reply_markup: {
"inline_keyboard": [
[{
"text": "InlineFeatures.",
"callback_data": "inline_plugs_1118095942"
}],
[{
"text": "OtherFeatures.",
"callback_data": "other_plugs_1118095942"
}]
]
}
},
//inline result of a cached telegram document with inline keyboard
{
id: "nchgffjdfgd",
title: 'title',
description: "description",
//change this on with the value of file_id from telegram bot api
document_file_id: "BQACAgQAAxkBAAIBX2CPrD3yFC0X1sI0HFTxgul0GdqhAALjDwACR4pxUKIV48XlktQNHwQ",
type: 'document',
caption: "caption ghh hhdd",
reply_markup: {
"inline_keyboard": [
[{
"text": "InlineFeatures.",
"callback_data": "inline_plugs_1118095942"
}],
[{
"text": "OtherFeatures.",
"callback_data": "other_plugs_1118095942"
}]
]
}
}
])
})
function tgmsg(method, data) {
var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(data)
};
var responselk = UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/' + method, options);
}

Parsing json_callback response from server Angular 4

Using Angular 4, I sent a get request to this url https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK&format=json&tagmode=all&tags=test
with following code,
this.http.get('https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK', {
params: { format: 'json', tagmode: 'all', tags: query }
})
.subscribe(data => {
console.log(data);
});
The response I get is in the following format, wrapped as a method argument.
JSON_CALLBACK({
"title": "Recent Uploads tagged test",
"link": "https:\/\/www.flickr.com\/photos\/tags\/test\/",
"description": "",
"modified": "2018-02-04T14:51:42Z",
"generator": "https:\/\/www.flickr.com",
"items": [
{
"title": "Desktop2018-02-04-14_39_44.jpg",
"link": "https:\/\/www.flickr.com\/photos\/besnaveld\/28298869359\/",
"media": {"m":"https:\/\/farm5.staticflickr.com\/4769\/28298869359_e932760377_m.jpg"},
"date_taken": "2018-02-04T06:51:42-08:00",
"description": " <p><a href=\"https:\/\/www.flickr.com\/people\/besnaveld\/\">besnaveld<\/a> posted a photo:<\/p> <p><a href=\"https:\/\/www.flickr.com\/photos\/besnaveld\/28298869359\/\" title=\"Desktop2018-02-04-14_39_44.jpg\"><img src=\"https:\/\/farm5.staticflickr.com\/4769\/28298869359_e932760377_m.jpg\" width=\"240\" height=\"135\" alt=\"Desktop2018-02-04-14_39_44.jpg\" \/><\/a><\/p> ",
"published": "2018-02-04T14:51:42Z",
"author": "nobody#flickr.com (\"besnaveld\")",
"author_id": "154665852#N05",
"tags": "test booth"
} ]
})
How can I extract the data inside this JSON_CALLBACK function argument?
based on filckr document simply add
nojsoncallback=1 -> {...}
jsoncallback=wooYay -> wooYay({...});
to your request to get it right . then your url should be :
https://api.flickr.com/services/feeds/photos_public.gne?nojsoncallback=1&format=json&tagmode=all&tags=test

How to map json data coming from an REST-API to ember.js model?

I'm new to EmberJS and try to connect my EmberJS-frontend to an API via the RESTAdapter. I'm using ember-1.0.0-rc.6 and ember-data-latest (Version: v0.13-59-ge999edb).
From the API I get the following JSON code:
{
"page": 1,
"limit": 5,
"total": 4,
"results": [
{
"id": 1,
"title": "something3",
"description": "asd3"
},
{
"id": 2,
"title": "something3",
"description": "asd3"
},
{
"id": 3,
"title": "something2",
"description": "asd2"
},
{
"id": 4,
"title": "something",
"description": "asd"
}
]
}
My RESTAdapter looks like the following:
App.Store = DS.Store.extend({
revision: 13,
adapter: DS.RESTAdapter.extend({
url:"http://localhost/api/app_dev.php"
})
});
My model looks like this at the moment:
App.Modelname = DS.Model.extend({
title: DS.attr('string')
});
With this I get the following error in the browser console:
Assertion failed: Your server returned a hash with the key page but you have no mapping for it
MY question is how to connect the json output from the api to my ember model without changing the api on the server?
Thanks in advance for your support !
If your model is like this:
App.Modelname = DS.Model.extend({
title: DS.attr('string')
});
Then the RESTAdapter expects a JSON format like this:
{
"modelNames": [
{
"id": 1,
"title": "something3",
"description": "asd3"
},
{
"id": 2,
"title": "something3",
"description": "asd3"
},
{
"id": 3,
"title": "something2",
"description": "asd2"
},
{
"id": 4,
"title": "something",
"description": "asd"
}
]
}
You can of course tweak some of this behavior by configuring some aspects of the JSONSerializer and the RESTAdapter, IMO to have full control I would suggest to create your own adapter by overriding the vital functions like find, findAll etc. and go with plain $.ajax(...). Otherwise you would need to make your backend obey the JSON format ember-data expects.
Hope it helps, at least to take a decision.

Ember.js / nested json / cannot get data displayed

making first attempt to master Ember.js atm. I'm trying to make a simple CMS, but for some reason I have a problem with getting any data from json displayed. I've already switched from Fixture to RESTAdapter, but I am still stuck with
Error: assertion failed: Your server returned a hash with the key timestamp but you have no mapping for it.
Here's my js code:
App.Store = DS.Store.extend(
{
revision:12,
adapter: 'DS.RESTAdapter'
}
);
App.Menucategory = DS.Model.extend({
timestamp: DS.attr('number'),
status: DS.attr('string')
});
App.MenucategoryRoute = Ember.Route.extend({
model: function() {
return App.Menucategory.find();
}
});
DS.RESTAdapter.reopen({
url: <my url>
});
DS.RESTAdapter.configure("plurals", {
menucategory: "menucategory"
});
Trying to access it with:
<script type="text/x-handlebars" id="menucategory">
{{#each model}}
{{data}}
{{/each}}
</script>
My json structure:
{
"timestamp": 1366106783,
"status": "OK",
"data": [
{
"name": "starters",
"id": 1
},
{
"name": "main dishes",
"id": 2
}]}
Thank you in advance for any help you can provide.
By default the RESTAdapter expects your API to be in a specific format, which your API doesn't conform to, if you can modify your API, you need to get it to return in this format, otherwise you'll need to customize the adapter.
Expected Format (based on your JSON):
{
"menucategory": [
{
"name": "starters",
"id": 1
},
{
"name": "main dishes",
"id": 2
}
],
"meta": {
"timestamp": 1366106783,
"status": "OK",
}
}