Passing an array of object having name and value attribute as query param - rest

Here is scenario.
I have below pojo
Property {
String name;
String value;
}
I want to pass an array of above pojo as query param. How do i do that.
Something like
http://myservice.com?property:name=n1&property:value=v1&property:name=n2&property:value=v2
And I want to figure out at service end that v1 is the value for n1.
Is there a way to achieve this.

One way that you can pass this into a URL as the following -
sample.php?arr_args[key1]=value1&arr_args[key2]=value2

Related

HTTP PATCH method in golang

I am implementing a HTTP PATCH method in golang and postgresql, I need to read the data from the request and update the data provided into the postgresql.
The method works fine if all the values of the struct is provided, but if only partial data is given to a request, the other fields are becoming empty. Can anyone please help me out to deal this problem.
type StudentDetails struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Class int `json:"class"`
}
Query which I am using "UPDATE table_name SET name=$2, age=$3, class=$4 WHERE id=$1"
If all the fields given in the request this works fine, but if I need to update only the AGE and the request json would be {"age": 10} or some other field we dont know. Here Age is set to 10 but remaining all fields will become "" or 0 and that will be updated into the database
Anyone has the solution to this problem, how to update the requested field only and not change other fields.
I have approached using a separate query for all fields, but I think its not the proper one. Please give me a solution
Like what #David Hall said in the comments, use pointer to a type in the fields of your struct. See example below:
type ArticleModel struct {
gorm.Model
ID uuid.UUID `gorm:"primaryKey;type:uuid"`
Title *string
Body *string
}
I am using gorm, then when unmarshalling the json from http request you will get nil value if not provided. You need to add nil checkers to skip in the construction of your SQL query. Something like this.
if entity.Title != nil {
model.Title = entity.Title
}
if entity.Body != nil {
model.Body = entity.Body
}
db.Save(&model)
Now the next problem would be how to intentionally empty the field in database (explicitly nulling the value) like UPDATE table SET field = null. Unfortunately I haven't figured it out also.
What I have in mind is checking if empty string and considering it as the setting it to empty value. Although I want to see better options.

Postgres jsonb_set concatenate current value

I'm trying to use jsonb_set to update a range of json objects within my database. I can get a query working that updates the object with a string value, however I cannot seem to get it to update using the current value.
UPDATE entity
SET properties = jsonb_set(properties, '{c_number}', concat('0', properties->>'c_number'))
WHERE type = 1 and length(properties->>'c_number') = 7
The above doesn't work in its current format, I think the issue is the properties->>'c_number' inside the jsonb_set. Is there a way I can access the current value and simply add a leading 0?
Found a solution:
UPDATE entity
SET properties = jsonb_set(properties, '{c_number}', concat('"0', properties->>'c_number', '"')::jsonb)
WHERE type = 1 and length(properties->>'c_number') = 7
Based on this answer I was able to prepare my solution.
My goal was to create a new property in JSON, with a value that is based on the value of one of the properties which my JSON already has.
For example:
I have:
{
property_root: { property_root_child: { source_property_key: "source_property_value" } }
}
I want:
{
property_root: { property_root_child: { source_property_key: "source_property_value", target_property_key: "source_property_value + my custom ending" } }
}
So my query would look:
UPDATE database.table_with_json
SET json_column=jsonb_set(
json_column,
'{ property_root, property_root_child, target_property_key }',
concat('"', json_column->'property_root'->'property_root_child'->>'source_property_key', ' + my custom ending', '"')::jsonb)
WHERE
json_column->'property_root'->'property_root_child'->'source_property_key' IS NOT NULL
Why concat looks messy? Based on the answer mentioned above:
The third argument of jsonb_set() should be of jsonb type. The problem is in casting a text string to jsonb string, you need a string in double quotes.
That is why we have to wrap concat in double qoutes.

Using a variable as a Map key MongoDB Groovy Query

I've a mongo db query to fetch some data as shown below
collection.find(lastUpdated: ['$gte': startDate.toLong(), '$lt': endDate.toLong()], resource: ['$gt': limit]).findAll().toList()
resource is a dynamic field which could have values like:
parameter1, parameter2 ... and so on.
I'm passing resource as method parameter in this query.
Can somebody suggest some way through which I can dynamically use resource without hard coding its value as (paramter1 or parameter2 or parameter3 ...) in my query
yeah you are almost there you just need to pass it as a variable and use () syntax on the Map to indicate that you are using a variable as a key instead of a literal value.
change this:
resource: ['$gt': limit]
to this:
(resource): ['$gt': limit]
Full query:
def resource = "parameter1"; //or parameter2 ...
collection.find(lastUpdated: ['$gte': startDate.toLong(), '$lt': endDate.toLong()], (resource): ['$gt': limit]).findAll().toList()

Is it possible to be able to accept many matrix parameters in my rest URL without having to declare them in my code?

I am developing a Restful WS which does the simple job of querying a DB and bringing back some data. The table that is querying has around 20 columns.
I want to be able to filter the my returned records by using the matrix parameters in the WHERE clause of my SQL statements.
For Example:
Lets say that we have the table People with the columns id, firstname, lastname
I want the URL http://localhost:808/myservice/people;firstname=nick
to bring me back all the people with firstname equals Nick (select * from people where firsname='Nick').
First of all, is this the correct practice to do that?
Second, in my tablet that I have 20 columns I must create a method in my Java code that will contain all the possible matrix parameters (see below) or there is a better way to do this?
public Response getPeople(#MatrixParam("id") String id,
#MatrixParam("firstname") String firstname,
#MatrixParam("lastname") String lastname,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,
#MatrixParam("antoherColumn") String antoherColumn,) {
}
Thanks in advance
First of all do not create your query by concatenating strings:
String q = "select * from where firstName = " + firstName //BAD!
You are asking for troubles like SQL injection attacks. If you use JDBC, use query parameters.
Since probably you want to use GET request, you can stick to your approach, use query parameters instead (#QueryParam). You might also consider the following approach:
http://localhost:808/myservice/people?filter=firstname:nick,lastName:smith
and method:
public Response getPeople(#QueryParam("filter") String filter) {
//if filter is not null, tokenize filter string by ',' then by ':'
//to get needed parameters
}
You should use #BeanParam in order to map the MatrixParam to an object.
This way you can keep the resource pretty simple, but still have the possibility to add more matrix parameters. Also, adding matrix params doesn't involve changing the resource at all. The #BeanParam works also with #PathParam and #QueryParam.
Example:
Consider this:
http://localhost:8081/myservice/people;firstname=nick,lastName=smith/?offset=3&limit=4
and then the resource:
#GET
public Response get(#BeanParam Filter filter, #BeanParam Paging paging) {
return Response.ok("some results").build();
}
and the Filter class looks like:
public class Filter {
public Filter(#MatrixParam("firstname") String firstname, #MatrixParam("lastname") String lastname) {}
}
and the Paging class:
public class Paging {
public Paging(#QueryParam("offset") int offset, #QueryParam("limit") int limit) { }
}
You can also use more filters, like Filter1, Filter2 etc in order to keep it more modular.
Using the matrix parameters the biggest advantage is caching. It makes even more sense if you have more than one level in you API, like ../animals;size=medium/mamals;fur=white/?limit=3&offset=4, because the query params would apply otherwise to all collections.

Conversion of a object into a particular datetime format

I want to convert a query string object into a datetime in this format:- "YYYY-mm-dd HH:mm:ss.xxx" in C#.net. But when i am using Convert.ToDateTime(object) for getting the datetime value then an exception is being fired.
Could anyone can provide me the iFormatProvider for the same.?
Thanks
Varun Sareen
Have a look at DateTime.TryParseExact Method
I think your problem is trying to convert the QueryString object, instead of getting a value from the query string and then converting the value.
A QueryString object is a keyed collection of the values specified in a URL from an HTTP request. So if you have a URL like: http://example.com?a=1&b=2&c=3, the request QueryString object will contain three values: 1, 2, and 3. To access the values you would use the keys:
var aValue = Request.QueryString["a"];
And the variable aValue would then contain the string value "1" (without the quotes).
After getting the value from the query string, you can use the TryParseExact method suggested by #astander.