Laravel Api resource controller json format - laravel-5

I managed to change the format for the json response of the laravel resource controller for APIs, i want to make a key -> value response but i cant find the way to remove the brackets:
the response i get is this:
{
"1": [
{
"updated_at": 1536147154
}
],
"2": [
{
"updated_at": 1536160598
}
]
}
but i want it to be like this:
{
"1":
{
"updated_at": 1536147154
},
"2":
{
"updated_at": 1536160598
}
}
I get the response from an eloquent collection, and then I group it by id, but I don't know how to get rid of the brackets because the values end in an array.
I don't know if I am clear in my question.

Solved it, i removed the groupby and instead, I used the keyBy to assign their id as a key.

Transformers can be used to format json
I used https://github.com/spatie/laravel-fractal to format my json response in controllers

Related

How to handle JSON array response while using APIConsumer?

Using the APIConsumer contract we can feed data from API to the smart contract.
Eg: If the server response is:
{
"RAW":{"ETH":{"USD":{"VOLUME24HOUR": 10000,}}}
}
Then, data can be obtained as:
request.add("get", URL);
request.add("path", "RAW.ETH.USD.VOLUME24HOUR");
Similarly, If the server response contains some JSON array,
Eg:
{
"date":"530934083405834",
"results": [
{
"id": 9865,
"rank":1
},
{
"id": 9869,
"rank": 2
},
{
"id": 9866,
"rank": 3
}
]}
Then in this case is there a way to get the id of the rank 1 i.e results[0]["id"]?
To get results[0]["id"] your path in the request needs to be
request.add("path", "results.0.id");

How to use the "nextToken" parameter to test Pagination?

I am working with a sample of graphql query which I want to further bind to a FlatList object in a React-Native app. But I am still struggling to understand what I should pass on then nextToken parameter in order to get a slice of objects destined to a second page...
Tried to pass the next or last id or index, but it didn't work - it asks me to provide a valid nextToken, which I don't know what kind of data it is.
I'm running through AppSynch console.
My query:
query ListResources(
$nextTokenPlants: String = "Orange Tree"
$limitPlants: Int = 3
) {
listResources {
items {
id
name
Plants(limit: $limitPlants, nextToken:$nextTokenPlants) {
items {
id
name
filterName
description
bath
tea
insence
children
}
nextToken
}
}
nextToken
}
}
This is the result I get:
{
"data": {
"listResources": {
"items": [
{
"id": "361dee16-d567-41ed-b1d4-9baa4a7ffdcc",
"name": "Plantas",
"Plants": null
}
],
"nextToken": null
}
},
"errors": [
{
"path": [
"listResources",
"items",
0,
"Plants"
],
"data": null,
"errorType": "DynamoDB:UserIllegalArgumentException",
"errorInfo": null,
"locations": [
{
"line": 9,
"column": 7,
"sourceName": null
}
],
"message": "com.amazonaws.deepdish.common.pagination.InvalidPaginationTokenException: Invalid pagination token given."
}
]
}
I expected to get a list of 3 of the itens stored on "Plants", starting from the "Orange Tree" onwards... Could anyone pls shed some light on it?
nextToken is a String that you get in the response when you send a request, looks like
eyJ2ZXJzaW9uIjoxLCJ0b2tlbiI6IkFRSUNBSGdtYVZObHlaR3FSa3hDRnFVWWdFeEZDM0FMY1JRdE9UOEt2dWFLMExzcjJ3RlBPMGdpcC96bjQ5VjFOVElKUng1M0FBQUNlVENDQW5VR0NTcUdTSWIzRFFFSEJxQ0NBbVl3Z2dKaUFnRUFNSUlDV3dZSktvWklodmNOQVFjQk1CNEdDV0NHU0FGbEF3UUJMakFSQkF4VEt5Myt3RUJuSzVSU2hsUUNBUkNBZ2dJc1lmdDk2WVVmQ053Tms2WGkxc3Z2bUgzSGFQZTdNTm1DQWhDcWJ5RFlydXZwTmR6WUNBQ0pJS1RZQlVWdk1xbU9EV2s2SVdLTzlqNmRhenNWZGZYTmFTQmxseE9yUS9BZWY0c2NpL1duWVUweWEyNCthZGQxcVNaMGZEWDZUdkJDak1XQjQ4QmhTQmxLejk2TFpiZ3pDN3dJTzVPRStFbUxHdVhRcURXcUpNZDM3Rm0yNUdiQVU1Tlg1YWVtWE1PbnVKSkZpTzA3U3ZhdUVZMWZwaXZCVU9pMHlxTVlIYk5PMkQ4aDZRVmQ4eW4yTXl3YU9UUHYwWFJZNitrakgvNGlyOWtrdlVXK1pvNFdOeDFBL2h1MlF4Z0lSczQ3d0xTT2NsaXk1Y3o0eFFzM2xqREhYL3M0TTVwT2phTCt0TGpYOUlWcGZCVW45bUgwWEw4ZEFkR0VZRGdjeWpMUHlPdWFnREVNMWR4M09neTg4NGJPclJ3VVgrRmM0UHpGekRqSHZjcjBGSVVXNEM2ZUxzYVRtRjNFakhLRk9ERllDWWkrQ01QNFg0a0dCdTFJQ3BLQjNJdEx2VTZHcUxNVDRMd3NJbkk4SVBhZm1MRnYxRTZDbWxxMnFKZ2wxY1BEVmR6MVFDc0Ezby9vR0VHUkI2VkJtc3VFSUFuOW10OVJzaWpyaklqUm5DQzlSWHA3NnA0WlhWanBJY0dSVU9GTktvZGNnMVpNbGV0a200clhBUGJacFZ5TDdkcnQyTXlEVERQd1crcjZsRHJUUVJJZzI4MEl3Y3ZkQzB1RWRrb0hqTlZPR0kwSWxsSnZ5RjRWTCtNNzRuWXcwNVNSWllJODdGcGdzR21LZjRvWVA1VG9temRVUUR0YWkrZVRJcUxGRjlGYzk0UUNwZlYrVlpmeVU0Mk4yTnRtNi9MYUhrZ08zdGRTUHN1bGhQWVRuMGRQNU5aWG5pODU1eGZyL1N2dDQ2VU0xb3I2UEE9PSJ9
and it has nothing to do with your table keys.
Let me explain now how does it work:
When you send the request for the first time, you don't send nextToken since you don't have it and then you get the first portion of your data.
When you receive that first portion, if there exist more data, you get nextToken in the response.
Now, you have nextToken, you send another request to get the 2nd portion of your data. You should send that token in the request, so your backend knows from where to start.
You get your 2nd portion of data and a new nextToken if there is still some data to fetch (then you need to repeat step 2) or null in nextToken if there is no more data.
I hope that it's clear now

How should I use redis?

I'm doing an api in laravel and I want to use Redis. I'm not sure if I'm doing well.
How should I use Redis to store json and then get a value by ID or another column.
Should I save the json as plain text? Then how do I go through it to look for a specific value or how you should keep the values?
{
"id": 1,
"name": "Package A",
"dimensions": "100x100x100",
"created_at": "2019-05-29 01:35:53",
"updated_at": "2019-05-29 01:35:53"
},
{
"id": 2,
"name": "Package B",
"dimensions": "150x150x150",
"created_at": "2019-05-29 01:36:53",
"updated_at": "2019-05-29 01:36:53"
}
$package = Package::where->get();
Redis::hmset('packages', array($package));
Or I shoud ..
$package = Package::where->get();
Redis::set('packages', serialize($package));
Then How I get a value?
For example: all fields id=2
I recommend saving the information in the following way, so it is easier to access later.
Package::all()->each(function($package){
Redis::set("package:{$package->id}", $package->toJson());
});
And if you need to recover information :
json_decode(Redis::get("package:$id"), true);
In redis you have to consider how to access the information, and then how to save it. For example, if you want to search by name, your key will be composed of the same name.
If you want retrive all packages from Redis, you will need all of packages key´s.
The folowing command retrive all keys matches with the structure :
Redis::keys('package:*');
After that, you can do the following
$keys = Redis::keys('package:*');
$packages = [];
foreach ($keys as $key){
array_push($packages, json_decode(Redis::get($key), true));
}
return $packages;

laravel/codeception : test if json response contains only certain keys

I have a json array coming from my api as response:
{
"data": [
{
"id": 1,
"name": "abc"
}
}
I am using laravel for api and laravel-codeception for testing.
public function getAll(ApiTester $I)
{
$I->sendGET($this->endpoint);
}
I have to test if the response contains only id and name key (not any other key) example this response should fail the test.
{
"data": [
{
"id": 1,
"name": "abc",
"email":"abc#xyz"
}
}
I have found $I->seeResponseContainsJson(), but it checks if JSON is present or not. It does not check if JSON response contains only specified keys.
Thanks.

Find matching array items in MongoDB document

I am developing a web app using Codeigniter and MongoDB.
In the database I got a document that look like this:
{
"_id": {
"$id": "4f609932615a935c18r000000"
},
"basic": {
"name": "The project"
},
"members": [
{
"user_name": "john",
"role": "user",
"created_at": {
"sec": 1331730738,
"usec": 810000
}
},
{
"user_name": "markus",
"role": "user",
"created_at": {
"sec": 1331730738,
"usec": 810000
}
}
]
}
I need to search this document using both user_name and role. Right now when I am using the below code I get both. I only want to get array items matching both user_name and role.
$where = array (
'_id' => new MongoId ($account_id),
'members.user_id' => new MongoId ($user_id),
'members.role' => $role
);
$this -> cimongo -> where ($where) -> count_all_results ('accounts');
This is an old question, but as of MongoDB 2.2 or so you can use the $ positional operator in a projection so that only the matched array element is included in the result.
So you can do something like this:
$this->cimongo->where($where)->select(array('members.$'))->get('accounts');
This is a repeat of this question:
Get particular element from mongoDB array
Also you might want to use $elemMatch
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray
Here is the rub -- you aren't going to be able to get the array items that match because mongo is going to return the entire document if those elements match. You will have to parse out the code client side. Mongo doesn't have a way to answer, "return only the array that matches."

Resources