fix #257 Adding option to set the obj id from a non JSON response - #263
fix #257 Adding option to set the obj id from a non JSON response#263S3B4SZ17 wants to merge 3 commits into
Conversation
… we can identify we are not getting a formatted JSON response object If we get a response as a string or int we are assigning that response as the id of the obj. We need to set the `id_attribute` to `*`
* Adding a Makefile for simplicity to build the project and clean it, also to run the tests more easily * Updated the fakeserver so we can test the new func for non JSON responses
|
Apologies for the slow reply, but I perhaps don't understand the scenario. Does the API in question support the creation and update of an object with JSON data, but itself only returns the ID on creation? That seems like a very strange API. Any docs you can link to? |
|
No problem :) This is a weird scenario and could be a lousy API implementation scenario, but we still have scenarios like this. In this case, it will address the following issue #257 where the response of the server will be an id string instead of a proper JSON object: # server response
"virtualwire-12"
# What the response should be but there are third APIs that do it that way
{"id": "virtualwire-12"} |
| /* Checking if the response is not a normal JSON but probabbly an int or string and the id_attribute is set to '*' | ||
| Setting that response value as the ID */ | ||
| var result interface{} | ||
| err = json.Unmarshal([]byte(resultString), &result) |
There was a problem hiding this comment.
Today I learned that the Go JSON Unmarshal routine will accept non-JSON values!
There was a problem hiding this comment.
I believe due to this:
To unmarshal JSON into a value implementing Unmarshaler, Unmarshal calls that value's [Unmarshaler.UnmarshalJSON] method, including when the input is a JSON null. Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls encoding.TextUnmarshaler.UnmarshalText with the unquoted form of the string.
Which begs the question - what happens when the text isn't encapsulated with "s? It turns out that go doesn't seem to like that. This kinda takes me back to the question about the API implementations for this odd use case. Will all such APIs encapsulate their response in "s or is there a reasonable scenario where the ID will just be the full text of the response body?
Summary
Addressing the #257 issue. If an API response with a non JSON formatted obj (a string or int i.e
1234ormy-string) we are going to use that value as the tf obj id. We need to set theid_attributeoption as*.Example
Example non-JSON response from the fakeserver:
curl 127.0.0.1:8080/api/objects -X POST -d '{ "Id": "1", "Name": "Foo", "No_json": true}' 1That
1will be used as the Obj IDTests
Under
restapi/api_object_test.gocreated thecreate_object_no_json_responsetest case