Convert response to JSON response standard in Nestjs - json

I have a problem converting the result of my object after saving it to the database, because I tried to follow the recommendations of https://jsonapi.org/ and convert my answers to the Json standard.
The implementation I did is not the best. This is:
async findAll() {
const data = new DataResponse<Product>();
return await this.repository.find().then(value => {
data.data = value;
data.isError = false;
data.message = "";
data.statusCode = 1;
return data;
}).catch(e => {
const error: HttpException = e;
data.data = [];
data.isError = true;
data.message = error.message;
data.statusCode = error.getStatus();
return data;
});
}
My json response I have this is:
{
"data": {
"id": 1,
"description": "Oreo",
"price": "6.5",
"category": "Oreo",
"stock": 50,
"createDate": "2021-10-28T14:11:47.454Z",
"lastUpdateDate": "2021-10-28T14:11:47.454Z"
},
"message": "",
"statusCode": 1,
"isError": false
}

why not to make a DTO or initalize and object of entity like new Product(),
and then assign values if you want to save them in Database rather than stringified JSON Objects?. this would resolve your problem.

Related

how to send data to the internet HTTP Post request using flutter ( fixed )

FIXED, CHECK THE CODE IN MY OWN ANSWER BELOW
Hello dear Stackoverflow community, i'm kinda new to flutter and i can't really understand this problem i'm getting while trying to send a post request from the flutter app
_CastError (type '_InternalLinkedHashMap<String, String>' is not a subtype of type 'String' in type cast)
here is my code
sendForm() async {
var jsonResponse;
// the error line is below, in the http method
var response = await http.post(
"https://promoteur-api.herokuapp.com/api/messages",
body: {
// update
// the problem is in the message":{...} it makes it Map<String, String> instead of String
"message": {
"nom": nomController.text,
"prenom": prenomController.text,
"tel": telController.text,
"email": emailController.text,
"sujet": sujetController.text,
"message": messageController.text
}
},
);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
setState(() {
isLoading = false;
});
}
} else {
setState(() {
isLoading = false;
});
print(response.body);
}
}
and i'm calling the method here
onPressed: () {
sendForm();
},
here is the request in postman :
{
"message": {
"nom": "Testing name",
"prenom": "Testing name",
"tel": "25252525",
"email": "testing#gmail.com",
"sujet": "Testing subject",
"message": "something here"
}
}
and the response :
{
"id": 6,
"nom": "Testing name",
"prenom": "Testing name",
"tel": 25252525,
"email": "testing#gmail.com",
"sujet": "Testing subject",
"message": "something here"
}
Might look frightening but _InternalLinkedHashMap is just the internal LinkedHashMap class which is just the default Map implementation.
Somewhere in your code you must have wrongly placed a map object into a string type parameter.
Because the only statically typed part of your sendForm function is the function parameters itself I think you have passed a Map object to it. -> maybe check what you passed to that function :)
this code works perfectly
I needed to pass the map the body twice as u can see in the code and to json encode it afterwards,
then i had to pass the header params as it follow here
{'Content-type': 'application/json'}
Full code :
sendForm() async {
var jsonResponse;
Map data = {
"nom": nomController.text,
"prenom": prenomController.text,
"tel": telController.text,
"email": emailController.text,
"sujet": sujetController.text,
"message": messageController.text
};
Map body = {"message": data};
var response = await http.post(
"https://promoteur-api.herokuapp.com/api/messages",
body: jsonEncode(body),
headers: {'Content-type': 'application/json'},
);
print(response.statusCode);
if (response.statusCode == 200) {
jsonResponse = jsonEncode(response.body);
if (jsonResponse != null) {
print(response.body + " jsonResponse is not null");
setState(() {
isLoading = false;
});
}
} else {
setState(() {
isLoading = false;
});
print(response.body + "error jsonResponse = null");
}
}

Angular Getting Value from Object Object

I would like to extract the value from the JSON below (resReturn.result.gamingdata.original.success)
Just wonder why I can get the value only if I do several times of stringify and parse.
Can someone tell me how to simplify my code?
JSON:
{
"status":"Success",
"message":"100",
"resReturn":
{
"result":{
"gamingdata":
{
"headers":{},
"original":{"success":"Gaming Data Excel - upload success"},
"exception":null
}
}
}
}
My Code:
let resReturnJSON = JSON.stringify(this.UploadstatusGamingDataExcel.resReturn);
let resultobj = JSON.parse(resReturnJSON || '{}').result;
let resultJSON = JSON.stringify(resultobj);
let gamingdataobj = JSON.parse(resultJSON || '{}').gamingdata;
let gamingdataJSON = JSON.stringify(gamingdataobj);
let originalObj = JSON.parse(gamingdataJSON || '{}').original;
let originalJSON = JSON.stringify(originalObj);
let successObj = JSON.parse(originalJSON || '{}').success;
console.log(successObj);
const value = {
"status": "Success",
"message": "100",
"resReturn":
{
"result": {
"gamingdata":
{
"headers": {},
"original": { "success": "Gaming Data Excel - upload success" },
"exception": null
}
}
}
}
const jsonValue = JSON.stringify(value);
const valueFromJson = JSON.parse(jsonValue);
const success = (((((valueFromJson || {}).resReturn || {}).result || {}).gamingdata || {}).original || {}).success;
Check for truthiness for every property until you hit success property and return if found or return empty string.
const data = {
"status": "Success",
"message": "100",
"resReturn": {
"result": {
"gamingdata": {
"headers": {},
"original": {
"success": "Gaming Data Excel - upload success"
},
"exception": null
}
}
}
};
const success = (data.resReturn &&
data.resReturn.result &&
data.resReturn.result.gamingdata &&
data.resReturn.result.gamingdata.original.success) ?
data.resReturn.result.gamingdata.original.success : '';
console.log(success);
If you want a generalised function for json having array and objects, you can use this,
const data = {
"status": "Success",
"message": "100",
"resReturn": {
"result": {
"gamingdata": {
"headers": {},
"original": {
"success": "Gaming Data Excel - upload success"
},
"exception": null
}
}
}
};
const get = (p, o) =>
p.reduce((xs, x) =>
(xs && xs[x]) ? xs[x] : null, o)
console.log(get(['resReturn', 'result', 'gamingdata', 'original', 'success'], data));
I have one more simplest solution:
let obj: any;
try {
if (data.resReturn.result.gamingdata.original.success) {
obj = data.resReturn.result.gamingdata.original.success
}
} catch(e) {
obj = null
}
console.log(obj);
For other different ways, you can also refer this answer

How to access values from JSON response which is in [object Object], [object Object] in Angular 6

I have a JSON response , Below is my response.
{
"data": [
{
"2": [
{
"name": "Test1",
"Address": "Test2"
},
]
},
{
"5": [
{
"name": "Test3",
"Address": "Test4"
},
]
},
]
}
I am able to access till data from the response.Here "2" and "5" are date.If one date is present in this json response then for that response i have to get name and address
But I have to show list of data.
<div *ngFor = "let data of result">
<span>{{data.name}}</span>
<span>{{data.Address}}</span>
</div>
In ts file,
let result = response.data;
I want to access name and address from this.Can anyone please help me how to do this.
You can use Object.key, map and concat function to flat your data like this
let obj = this.result;
this.result = Object.keys(obj).map(function (key) {
let objkey = obj[key];
let first = Object.keys(objkey)[0]
return obj[key][first];
});
this.result = [].concat.apply([], this.result);
Demo at https://stackblitz.com/edit/angular-flat-array-property
Updated:
I update demo with filter to apply your filter by date.
let obj = this.result;
var filter = '5';
this.result = Object.keys(obj).map(function (key) {
let objkey = obj[key];
let first = Object.keys(objkey)[0]
if(filter == first){
return obj[key][first];
}else{
return null;
}
});
this.result = [].concat.apply([], this.result.filter(c=>c != null));

Angular Typescript access specific JSON object by id in an observable

I have this json string below and I want to either pull the "stocks" data array or the "contacts" data array based on whichever one I need for a given request:
[{
"id": "stocks",
"name": "Stocks",
"data": [
{
"id": 1,
"name": "Actuant Corporation",
"symbol": "ATU"
},
{
"id": 2,
"name": "Xilinx, Inc.",
"symbol": "XLNX"
}
]
},
{
"id": "contacts",
"name": "Contacts",
"data": [
{
"id": 1,
"full_name": "Betty Traise"
},
{
"id": 2,
"full_name": "Hank Hurrion"
},
{
"id": 3,
"full_name": "Calvin Ommanney"
}
]
}]
For example, in the function below, which is an observable, assume the payload argument is "contacts". In that case, I need to return the "id: "contacts" data array. Here's the code I'm using:
loadData$(payload: any = {}): Observable<any> {
// paths: {
// titlemaps: 'http://localhost:4100/data'
// },
// return this.service.get(this.config.paths.titlemaps, payload);
const JSON: any = this.service.get(this.config.paths.titlemaps, payload);
console.log('payload: ' + payload, 'json: ' + JSON); // if payload is "contacts", return only the contacts
return JSON.find(data => data.id === 'contacts');
}
The console log returns "contacts" and the entire JSON as expected. However, the JSON.find fails with error:
ERROR TypeError: JSON.find is not a function
When I switch the function types a bit, I get typescript compiler error:
[ts] Property 'find' does not exist on type 'Observable'.
What am I missing?
The result of your service call seems to be an observable, you can transform the result and return a new value with rxjs pipeable operators:
import { map } from 'rxjs/operators';
....
loadData$(payload: any = {}): Observable<any> {
return this.service.get(this.config.paths.titlemaps)
.pipe(
map(result => result.find(data => data.id === payload))
);
}
Hope it helps!
I moved the mapping/find operation to the service since you're passing those as params but you don't have to do it like that of course...
https://stackblitz.com/edit/angular-2lajx4
The gist...
get(url, payload) {
return of(results)
.pipe(map((res: any) => {
return res.find(data => data.id === payload)
}));
}
Just using of() here to simulate an observable, results is the JSON you provided above...
loadData$ subs to the get and puts the data into a variable for consumption
data: any;
loadData$(payload: any = {}) {
this.service.get('../results.json', payload).subscribe(data => {
this.data = data
console.log('payload: ' + payload, 'json: ' + this.data); // if payload is "contacts", return only the contacts
});
}

how to change json format in asp.net mvc?

I'm trying to make autocomplete textbox using this link
https://github.com/devbridge/jQuery-Autocomplete
but I got this error
Uncaught TypeError: Cannot read property 'length' of undefined
this is my action method
public JsonResult GetNews(string prefix)
{
var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
{
value = n.Title,
data = n.Id
}).ToList();
var myjson = Json(newsList, JsonRequestBehavior.AllowGet);
return myjson;
}
and it return this result when I test it in browser
[{"value":"this is a test","data":2006}]
I found the format must be
{
suggestions: [{
"value": "United Arab Emirates",
"data": "AE"
}, {
"value": "United Kingdom",
"data": "UK"
}, {
"value": "United States",
"data": "US"
}, {
"value": "United Funes",
"data": "DAN"
}]
}
how can do this?
thanks a lot!
also as you can see I tried transformResult but it doesnt worked
<script>
$('#autocomplete').autocomplete({
serviceUrl: '/TestAutoComplete/GetNews',
paramName: 'prefix',
transformResult: function(response) {
return {
suggestions: $.map(response.myData, function(dataItem) {
return { value: dataItem.valueField, data: dataItem.dataField };
})
};
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
</script>
Try this, creates an anonymous object which just has the suggestions property
var newsList = NewsDataRoot.AutoCompleteTitle(prefix)
.Select(n => new {
value = n.Title,
data = n.Id
}).ToList();
var myjson = Json(new { suggestions = newsList }, JsonRequestBehavior.AllowGet);
if you want to set number to be numeric string you can try convert its value to string
public JsonResult GetNews(string prefix)
{
var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
{
value = n.Title,
data = n.Id.ToString()
}).ToList();
var myjson = Json(new {suggestions = newsList}, JsonRequestBehavior.AllowGet);
return myjson;
}