How to decode Logs and get back Events with web3? - ethereum

I have this transaction that emits 2 different events from 2 different contracts. Let's say I have the ABI files for both contracts, how can I parse the events out of the logs field?
For example, here is such transaction that emitted 2 events https://rinkeby.etherscan.io/tx/0xc6525195135a868897bd4c74ea0f6285b98492103be4df6fc5ea43f83b96b8eb#eventlog
And this is the respond of getTransactionReceipt RPC call, how can I parse the event names and their params out of the logs field?
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"blockHash": "0x3da27197fe084a82d76273b40c32e231d2662b229337795a43fde9f8d73b4d2c",
"blockNumber": "0x39a62b",
"contractAddress": null,
"cumulativeGasUsed": "0x48ad9",
"from": "0x20b53b91da0a2d9afdd442b2bb433a40ab7f9613",
"gasUsed": "0x9e36",
"logs": [
{
"address": "0x5328276603d169165d0f71ca67ccc89c45027df3",
"blockHash": "0x3da27197fe084a82d76273b40c32e231d2662b229337795a43fde9f8d73b4d2c",
"blockNumber": "0x39a62b",
"data": "0x000000000000000000000000f63843b0b7fc5097bc1f92658379617513cce546000000000000000000000000ff0e3299e55efd859176d582fc805481e83449150000000000000000000000000000000000000000000000000000000000002245",
"logIndex": "0x1",
"removed": false,
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
],
"transactionHash": "0x5442a15c593b3fcf3069ad7f6a41d8805a66a49ed407d872e46ea95b1c9f6054",
"transactionIndex": "0x3"
},
{
"address": "0x7387e0b25165e9a621f624e47b3362a937892c7b",
"blockHash": "0x3da27197fe084a82d76273b40c32e231d2662b229337795a43fde9f8d73b4d2c",
"blockNumber": "0x39a62b",
"data": "0x0000000000000000000000000000000000000000000000000000000000002245000000000000000000000000ff0e3299e55efd859176d582fc805481e8344915000000000000000000000000f63843b0b7fc5097bc1f92658379617513cce546000000000000000000000000000000000000000000000000016345785d8a0000000000000000000000000000000000000000000000000000000ffcb9e57d4000",
"logIndex": "0x2",
"removed": false,
"topics": [
"0x9accbcf984c4cd67a675ee4d38143974e1fa62aa95da283bd4ca645e408ec283"
],
"transactionHash": "0x5442a15c593b3fcf3069ad7f6a41d8805a66a49ed407d872e46ea95b1c9f6054",
"transactionIndex": "0x3"
}
],
"logsBloom": "0x20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000048000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000010000000000000000000000000000000000000000000000004000000000000000000080000008000000000000000000000000000000000000000400000000000000000000000000002000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"status": "0x1",
"to": "0x7387e0b25165e9a621f624e47b3362a937892c7b",
"transactionHash": "0x5442a15c593b3fcf3069ad7f6a41d8805a66a49ed407d872e46ea95b1c9f6054",
"transactionIndex": "0x3"
}
}

Related

How to multiple update a nested array within document at couchbase?

I have a bucket called chat which includes document model like
{
"id": "50542400778551298_5001_abcdef",
"customer": {
...
},
"seller": {
...
},
"complaints": [],
"messages": [
{
"id": "2828911d-b96f-4b90-a52c-252d0324ab69",
"owner": "SELLER",
"content": "Merhabalar",
"readingDate": null,
"createdAt": "2022-06-27T09:16:42.49158+03:00"
},
{
"id": "8cd8c4b7-d599-4dfa-9fa7-be304a3b72b9",
"owner": "SELLER",
"content": "İlan hakkında detay bilgi verir misin?",
"readingDate": null,
"createdAt": "2022-06-27T09:17:43.329741+03:00"
},
{
"id": "4f0ae912-7d65-4e79-9058-2b048c4d9845",
"owner": "SELLER",
"content": "Huhuu",
"readingDate": null,
"createdDate": "2022-06-27T09:18:37.491531+03:00"
},
{
"id": "d2dd61b3-7ff1-4139-a411-9a917c00d4f3",
"owner": "SELLER",
"content": "Orada kimse var mı?",
"readingDate": null,
"createdAt": "2022-06-27T09:18:45.917564+03:00"
},
{
"id": "ea2d8dca-2f8c-4987-9c07-7515a6a0063f",
"owner": "SELLER",
"content": "Döner misininiz?",
"readingDate": null,
"createdAt": "2022-06-27T09:18:52.80337+03:00"
}
],
"status": "ACTIVE"
}
I want to update all messages readingDate a specific time like (2022-06-27T09:18:52.80337+03:00)
But I cannot find an easy way to accomplish this task.
I tried to write an N1QL like
UPDATE c.messages SET c.messages.readingDate = NOW_LOCAL()
FROM chat AS c
WHERE META().id = '50542400778551298_5001_abcdef';
but it is not working and gives error
[
{
"code": 3000,
"msg": "syntax error - at SET",
"query": "UPDATE c.messages SET c.messages.readingDate = NOW_LOCAL()\nFROM chat AS c \nWHERE META().id = '50542400778551298_5001_abcdef';"
}
]
I saw https://docs.couchbase.com/server/current/guides/bulk-operations.html.
As far as to my understanding, the general solution gets all messages and updates them based on cas.
But maybe I believe there is an easy way so I wanted to ask the StackOverflow community.
Thanks to this question I wrote n1ql like
UPDATE chat USE KEYS '50542400778551298_5001_abcdef'
SET c.readAt = NOW_LOCAL() FOR c IN messages END
RETURNING messages;

Swift, JSON model

I have a question regarding building a JSON model namely, I should declare a date that will be different each day - in this case: "2020-11-19" as below.
This is a response for the current day.
{
"dates": {
"2020-11-19": {
"countries": {
"Poland": {
"date": "2020-11-19",
"id": "poland",
"links": [
{
"href": "/api/2020-11-19/country/poland",
"rel": "self",
"type": "GET"
}
],
"name": "Poland",
"name_es": "Polonia",
"name_it": "Polonia",
"regions": [],
"source": "John Hopkins University",
"today_confirmed": 796798,
"today_deaths": 12088,
"today_new_confirmed": 23975,
"today_new_deaths": 637,
"today_new_open_cases": 4335,
"today_new_recovered": 19003,
"today_open_cases": 422824,
"today_recovered": 361886,
"today_vs_yesterday_confirmed": 0.03102262743215456,
"today_vs_yesterday_deaths": 0.05562832940354556,
"today_vs_yesterday_open_cases": 0.010358695210626712,
"today_vs_yesterday_recovered": 0.055421236981710864,
"yesterday_confirmed": 772823,
"yesterday_deaths": 11451,
"yesterday_open_cases": 418489,
"yesterday_recovered": 342883
}
},
"info": {
"date": "2020-11-19 00:00CET",
"date_generation": "2020-11-19 22:34",
"yesterday": "2020-11-18 00:00CET"
}
}
},
"metadata": {
"by": "Narrativa & AppliedXL",
"url": [
"wwww.narrativa.com",
"www.appliedxl.com"
]
},
"total": {
"date": "2020-11-19",
"name": "Total",
"name_es": "Total",
"name_it": "Total",
"rid": "#total",
"source": "Narrativa",
"today_confirmed": 56684618,
"today_deaths": 1356365,
"today_new_confirmed": 525111,
"today_new_deaths": 8186,
"today_new_open_cases": 273944,
"today_new_recovered": 242981,
"today_open_cases": 19082735,
"today_recovered": 36245518,
"today_vs_yesterday_confirmed": 0.009350349175964112,
"today_vs_yesterday_deaths": 0.00607189401407382,
"today_vs_yesterday_open_cases": 0.014564678824917632,
"today_vs_yesterday_recovered": 0.00674899660543371,
"yesterday_confirmed": 56159507,
"yesterday_deaths": 1348179,
"yesterday_open_cases": 18808791,
"yesterday_recovered": 36002537
},
"updated_at": "2020-11-19 21:34UTC"
}
How I should build a model so that this property would be changed every day? (of course, this date needs to have a proper format "yyyy-MM-dd")
I would probably do:
var dates: [String: YourModel]
if it will potentially have multiple dates in that field.. otherwise, I'd probably do a custom object that overrides init(from decoder: and parses out that info

BlockCypher Send Transaction

I am trying to implement the BlockCypher Ethereum API following the docs here:
https://www.blockcypher.com/dev/ethereum/#transaction-api
I am using the Test Network /beth/test, rather than /eth/main.
I successfully created 2 addresses and called the faucet to fill one address with some 1000000000000000000 wei.
But then I can’t seem to be able to send a valid transaction…
Here are all (test) info:
ADDRESS 1
{
"private": "42eb005cbebd33f55b821864fcdc0755876317345ac9d8ad2bf94d734f78395f",
"public": "04c7238abb2e99c50ef3e4fabe21dbf2701f9dc60de24b40e743e84745984957ba7059a3e0b38c226b3580a95ed0e154fba407d089f5c02f90aa5797ead7fc190e",
"address": "7a9373010ce86d8fcd7dd46588d351cddabe7ce8"
}
ADDRESS 2
{
"private": "4a62456df43b89244d349948008064cfe1279ef3a632823f30b371ac54f879a1",
"public": "046c01b338e3c5224aa70fa302fefa5c9767d0f79aa16327e703d01924e894809460b22ab52974706543682d8e16063fd6cbd302b052762a3be5d7720efc4d2fa9",
"address": "73befec27510c64c303d82191eaf276a94603090"
}
Address 2 contains 1000000000000000000 wei, and I am trying to send 1200000000000000 wei to Address 1.
I use the New Transaction method, I send this:
{"inputs":[{"addresses": ["73befec27510c64c303d82191eaf276a94603090"]}],"outputs":[{"addresses": ["7a9373010ce86d8fcd7dd46588d351cddabe7ce8"], "value": 1200000000000000}]}
And I get this response:
{
"tx": {
"block_height": -1,
"block_index": 0,
"hash": "4e875a673e59f0b2d16123659b3a72a8d818a7cb832c5ed1a4bbf8f5b0a4ee87",
"addresses": [
"73befec27510c64c303d82191eaf276a94603090"
],
"total": 1200000000000000,
"fees": 21000000000000,
"size": 43,
"gas_limit": 21000,
"gas_price": 1000000000,
"received": "2018-05-27T13:51:23.247159854Z",
"ver": 0,
"double_spend": false,
"vin_sz": 1,
"vout_sz": 1,
"inputs": [
{
"sequence": 0,
"addresses": [
"73befec27510c64c303d82191eaf276a94603090"
]
}
],
"outputs": [
{
"value": 1200000000000000,
"addresses": [
"7a9373010ce86d8fcd7dd46588d351cddabe7ce8"
]
}
]
},
"tosign": [
"8b765bd6c2065f612eb00aa55c50759049779cff50151395aefc5a3dafa5cc10"
]
}
Then I use Signer with the ToSign from the New Transaction response, and a Hex-Encoded Private Key of Address 2:
signer 8b765bd6c2065f612eb00aa55c50759049779cff50151395aefc5a3dafa5cc10 34613632343536646634336238393234346433343939343830303830363463666531323739656633613633323832336633306233373161633534663837396131
I get this signature:
30440220644db87755b0a8620e7e52bd64977c79350c0989afd587090be13a8f76efbf3a0220463eb6351c839b086f5874f6a125ec4723fb30eb26a6a831600cb4d3034cd9d3
So then I try the Send Transaction method of BlockCypher, here’s my request:
{
"tx": {
"block_height": -1,
"block_index": 0,
"hash": "4e875a673e59f0b2d16123659b3a72a8d818a7cb832c5ed1a4bbf8f5b0a4ee87",
"addresses": [
"73befec27510c64c303d82191eaf276a94603090"
],
"total": 1200000000000000,
"fees": 21000000000000,
"size": 43,
"gas_limit": 21000,
"gas_price": 1000000000,
"received": "2018-05-27T13:51:23.247159854Z",
"ver": 0,
"double_spend": false,
"vin_sz": 1,
"vout_sz": 1,
"inputs": [
{
"sequence": 0,
"addresses": [
"73befec27510c64c303d82191eaf276a94603090"
]
}
],
"outputs": [
{
"value": 1200000000000000,
"addresses": [
"7a9373010ce86d8fcd7dd46588d351cddabe7ce8"
]
}
]
},
"tosign": [
"8b765bd6c2065f612eb00aa55c50759049779cff50151395aefc5a3dafa5cc10"
],
"pubkeys": ["046c01b338e3c5224aa70fa302fefa5c9767d0f79aa16327e703d01924e894809460b22ab52974706543682d8e16063fd6cbd302b052762a3be5d7720efc4d2fa9"],
"signatures": ["30440220644db87755b0a8620e7e52bd64977c79350c0989afd587090be13a8f76efbf3a0220463eb6351c839b086f5874f6a125ec4723fb30eb26a6a831600cb4d3034cd9d3"]
}
And I get back this error:
"Address 0xF6A14d976c86bDbe050cA9426aD491d750be33B1 computed from signature differs from provided one 73befec27510c64c303d82191eaf276a94603090."
Any idea of what am I doing wrong?
I tried several things already, read a few similar issues online, but still no luck.
I also tried the Raw Transaction method of BlockCypher, and also no luck there..
I am not clear what it means as “raw hex-encoded transaction”, I tried to send the Hex-Encoded input I sent to New Transaction:
{"inputs":[{"addresses": ["73befec27510c64c303d82191eaf276a94603090"]}],"outputs":[{"addresses": ["7a9373010ce86d8fcd7dd46588d351cddabe7ce8"], "value": 1200000000000000}]}
So I sent to https://api.blockcypher.com/v1/beth/test/txs/push?token=[mytoken] this:
{"tx":"22696E70757473223A5B7B22616464726573736573223A205B2237336265666563323735313063363463333033643832313931656166323736613934363033303930225D7D5D2C226F757470757473223A5B7B22616464726573736573223A205B2237613933373330313063653836643866636437646434363538386433353163646461626537636538225D2C202276616C7565223A20313230303030303030303030303030307D5D"}
But I get the error:
“rlp: expected input list for types.TxData”.
Please, any help is very much appreciated!
The private key you're passing to the signer tool is not correct. As Address 2 is the sender in your example, you should be using its private key instead, which is 4a62456df43b89244d349948008064cfe1279ef3a632823f30b371ac54f879a1.

Serialize the response from backend to store ember store

My response from backend is not in form which ember store. I am not able to serialize the response.
response.json
[{
"pk": 127,
"url": "http://example.com/api/galleries/127/",
"gallery_name": "Faces",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
"time": "1 month ago",
"description": "Created by user",
"is_following": true,
"feedPhotos": [{
"pk": 624,
"url": "http://example.com/api/photos/624/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
"comments_url": "http://example.com/api/photos/624/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
"fivers_pk": 1362,
"fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
"fullphoto_pk": 1362,
"is_fived": true,
"hiFiveKarma": 1,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 574,
"url": "http://example.com/api/photos/574/",
"profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
"userName": "Rohini",
"userKarma": 194,
"caption": "Life # Myanmar!",
"numComments": 0,
"owner": "http://example.com/api/users/45/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
"comments_url": "http://example.com/api/photos/574/comments/",
"numFives": 2,
"fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
"fivers_pk": 1303,
"fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
"fullphoto_pk": 1303,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 45,
"userFirstName": "Rohini",
"is_bookmarked": false
}
]
}, {
"pk": 65,
"url": "http://example.com/api/galleries/65/",
"gallery_name": "Royal",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
"time": "2 months ago",
"description": "This is a gallery about Royal",
"is_following": false,
"feedPhotos": [{
"pk": 347,
"url": "http://example.com/api/photos/347/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
"comments_url": "http://example.com/api/photos/347/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/759/fivers/",
"fivers_pk": 759,
"fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
"fullphoto_pk": 759,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 593,
"url": "http://example.com/api/photos/593/",
"profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
"userName": "Vikanshu",
"userKarma": 932,
"caption": "Marvelous architecture!! in Florence, Italy",
"numComments": 0,
"owner": "http://example.com/api/users/48/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
"comments_url": "http://example.com/api/photos/593/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
"fivers_pk": 1363,
"fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
"fullphoto_pk": 1363,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 48,
"userFirstName": "Vikanshu",
"is_bookmarked": false
}]
}]
How do I serialize this using JSONPISerailizer or any other serializer in ember-cli so that it gets stored in ember store
Reference jsonapi.org
++++Top Level:
Root:
A JSON object must be root of every JSON API request response.
A document must contain at least one top-level members:
1. data: documents "primary data"
2. errors: an array of error objects (id,status,code,title....)
3. meta: a meta object that contains non-standard meta-information (copyright,author...)
member data and errors must not co-exist together.
"data"{}
+++++Resource Objects
1. A resource object MUST contain atleast following top-level member
*id
*type
```
//structure-1
//for galleries
{
"data": {
"type": "galleries",
"id": "1"
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1"
}
}
```
In addition, a resource object may contain any of these top-level members
*attributes
*relationship
*links
*meta
//added attributes first
```
//structure-2
//for galleries
{
"data": {
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
}
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}
}
```
//Adding relationship
Relationship object must contain atleast one of the following
*links (containing atleast one of "self" or "related" resource link
*data
*meta
//link in relationship (minimum one required from link,data,meta).
//
```
//structure-3
//for galleries
{
"data":[{ //Array(square bracket as adding relationship one more item to data
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
}]
}
}
```
//data in relationship
```
//structure-4
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}]
}
}
```
//Adding related resource "included"
```
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},
{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
```
For collections. I am not confident but try this
Now for collection of galleries.
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
},{
"type": "galleries",
"id": "2",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "79"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "79",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
============Implementation part =================================
JSONSerializer normalization process follows these steps
*normalizeResponse : entry method.
*normalizeCreateRecordResponse : a normalizeResponse for specific operation.
*normalizeSingleResponse|normalizeArrayResponse:
- for methods like createRecord. we expect a single record back.
- for methods like findAll we expect multiple records back.
+normalize =
normalizeArray iterates and calls normalize for each of it's records
normalizeSingle call its once.
+extractID | extractAttributes | extractRelationships
= normalize delegates to these method to turn record payload into jsonAPI format
Starting with normalizeResponse method. If you open and see normalizeResponse method
in json-serializer
link normalizeResponse: https://github.com/emberjs/data/blob/v2.2.1/packages/ember-
data/lib/serializers/json-serializer.js#L192
you with find a switch case switch(requestType). If requestType if
"findRecord" then "normalizeFindRecordResponse" is called
"queryRecord" then "normalizeQueryRecordResponse" is called
"findAll" then "normalizeFindAllResponse" is called
...so on and so forth.
if you notice the parameter passed to all the methods are same as that of normalize
(...arguments) :)
**Lets start for findAll
i.e normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse
as normalizeFindAllResponse method has only one line that call
normalizeArrayResponse.
normalizeFindAllResponse
normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse ->
_normalizeResponse{ extractMeta,normalize }
extractMeta [extract meta information like pagination and stuff ]
if single: normalize []
example of normalize method in emberjs docs
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
"normalizeArrayResponse calls `return this._normalizeResponse
(store,primaryModelClass,payload,id,requestType,false).
so isSingle is false for _normalizeResponse method. so we will have to push all the
related records of included array
in our case the photos which is done by below snippet from "_normalizeRespose"
method.
_normalizeResponse
```
else{
documentHash.data = payload.map((item) => {
let { data, included } = this.normalize(primaryModelClass,item);
if(included){
documentHash.included.push(...included);
}
return data;
});
return documentHash;
}
```
Things are still unclear in the context of our JSON reponse from server
but atleast we know the flow now.
Lets try to apply it for findAll ( as per the flow above).
run "ember g serializer application" //assuming you are using ember-cli and you
intend to make this serializer generic for application.
As of now I have no information how and when normalizeResponse is called. :(
I just scanned through and guess on recieving data from server the store calls
normalizeResponseHelpers which in turn calls normalizeResponse.
In any case "normalizeResponse" is going to send payload and other necessar
information to normalizeFindAllResponse(...arguments) which in turn will call
normalizeArrayResponse(...arguments) which in turn will call "_normalizeRespone".
Here is where we need to take action
for extraMeta and normalize.
+extraMeta
I am not sure if there is any meta information in you json response.
in case there is you can refer to the example mentioned in docs
extractMeta
So I guess you can directly user the normalize method from example in your application ;).
please try and check. Since i am learning ember myself I cannot guarantee it will work but it should. the lonngggg explation is my thought while i was learning the problem/solution
//app/serializers/application.js
+normalize
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
The primary key in the JSON from server is pk. You will have to mention that too
http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: 'pk'
});

Backbone.js Collections

I am working with backbone.js. I am trying to send a request to restful service i am getting the resultset as json object as shown
{
"Msgs": [
"Alert",
"Not"
],
"MessageStatus": [
"Active",
"Inactive"
],
"date": {
"From": "2013-04-25",
"To": "2013-06-25"
},
"Mlist": {
"Status": "PND",
"Role": "Admin,User",
"To": "2013-06-24",
"Id": 6,
"Datecreated": "2013-06-24",
"Title": "Title5",
"From": "2013-06-20"
}
}.
I am putting the json object extracting and setting it to collection but I am not able to get particular model from the collection with specific id.
If you want to make your model can be identified with id. You have to set the id in the attributes hash:
{
"id": 1001,
"Msgs": [
"Alert",
"Not"
],
"MessageStatus": [
"Active",
"Inactive"
],
"date": {
"From": "2013-04-25",
"To": "2013-06-25"
},
"Mlist": {
"Status": "PND",
"Role": "Admin,User",
"To": "2013-06-24",
"Id": 6,
"Datecreated": "2013-06-24",
"Title": "Title5",
"From": "2013-06-20"
}
}
Then using backbone collection "findWhere" method to get the specific id model.
//assume msgCollection is which you put the models
var model = msgCollection.findWhere({id: 1001});
Hope this is helpful for you.
I think you need to set your model and parse your input data. Checkout http://backbonejs.org/#Collection-model, http://backbonejs.org/#Model-parse and http://backbonejs.org/#Collection-parse.