use of org.folio.rest.jaxrs.resource.support.ResponseDelegate in project raml-module-builder by folio-org.
the class PgUtil method postSync.
/**
* Post a list of T entities to the database. Fail all if any of them fails.
* @param table database table to store into
* @param entities the records to store
* @param maxEntities fail with HTTP 413 if entities.size() > maxEntities to avoid out of memory;
* suggested value is from 100 ... 10000.
* @param upsert true to update records with the same id, false to fail all entities if one has an existing id
* @param okapiHeaders http headers provided by okapi
* @param vertxContext the current context
* @param responseClass the ResponseDelegate class created from the RAML file with these methods:
* respond201(), respond409WithTextPlain(Object), respond413WithTextPlain(Object), respond500WithTextPlain(Object).
* @return future where to return the result created by responseClass
*/
public static <T> Future<Response> postSync(String table, List<T> entities, int maxEntities, boolean upsert, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseClass) {
final Method respond500;
try {
respond500 = responseClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return response(e.getMessage(), null, null);
}
try {
Method respond201 = responseClass.getMethod(RESPOND_201);
Method respond409 = getRespond409(responseClass);
Method respond413 = responseClass.getMethod(RESPOND_413_WITH_TEXT_PLAIN, Object.class);
if (entities != null && entities.size() > maxEntities) {
String message = "Expected a maximum of " + maxEntities + " records to prevent out of memory but got " + entities.size();
return response(message, respond413, respond500);
}
// RestVerticle populates a single record only, not an array of records
Promise<Response> promise = Promise.promise();
MetadataUtil.populateMetadata(entities, okapiHeaders);
PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders);
Handler<AsyncResult<RowSet<Row>>> replyHandler = result -> {
if (result.failed()) {
if (PgExceptionUtil.isVersionConflict(result.cause())) {
Method method = respond409 == null ? respond500 : respond409;
response(result.cause().getMessage(), method, respond500).onComplete(promise);
} else {
response(table, /* id */
"", result.cause(), responseClass, respond500, respond500).onComplete(promise);
}
}
response(respond201, respond500).onComplete(promise);
};
if (upsert) {
postgresClient.upsertBatch(table, entities, replyHandler);
} else {
postgresClient.saveBatch(table, entities, replyHandler);
}
return promise.future();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return response(e.getMessage(), respond500, respond500);
}
}
Aggregations