I have created a google cloud endpoint api which takes one record at a time as a JSON. Following is the insertMethod
@ApiMethod(name = "insertRecord")
public Record insertRecord(Record record) {
PersistenceManager mgr = getPersistenceManager();
try {
if(record.getSyncTime() == null)
record.setSyncTime(new Date());
mgr.makePersistent(record);
} finally {
mgr.close();
}
return error;
}
If we post a JSON in below format, it would add the record in data store.
{
ipAddress: "123.456.789.098",
user: "buddha",
message: "testing a single record adding"
}
I'm curious to know How I can write the method that would take multiple records in a single JSON request?
I tried changing method to take a List but I got an error saying that I should not pass Array or List.
After some trial and errors, I have solved the problem by following below Approach.
I have created another Class that contains a List of Records as below.
public class RecordList {
List<Record> records;
public List<Record> getRecords() {
return records;
}
public void setRecords(List<Record> records) {
this.records= records;
}
}
I have created another API method that takes this this new object as a parameter
@ApiMethod(name = "insertRecordList")
public RecordList insertRecordList(RecordList records) {
PersistenceManager mgr = getPersistenceManager();
try {
for(Record record : records.getRecords()){
if(record.getSyncTime() == null)
record.setSyncTime(new Date());
}
mgr.makePersistentAll(records.getRecords());
} finally {
mgr.close();
}
return records;
}
With this, I'm able to pass JSON request as below to insert multiple items at once...
{
records:[
{
"host": "testlist",
"ipAddress": "sadf",
"message": "testlist"
},
{
"host": "h",
"ipAddress": "1",
"message": "another"
}
]
}