Skip to content

Commit

Permalink
#126 - add GET/PATCH /configs API endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
mfriesen committed May 19, 2023
1 parent b5a05db commit afbce42
Show file tree
Hide file tree
Showing 9 changed files with 460 additions and 169 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
*/
package com.formkiq.aws.dynamodb;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
Expand Down Expand Up @@ -60,6 +62,14 @@ public interface DynamoDbService {
*/
Map<String, AttributeValue> get(AttributeValue pk, AttributeValue sk);

/**
* Batch Get a number of Keys.
*
* @param keys {@link Collection}
* @return {@link List}
*/
List<Map<String, AttributeValue>> getBatch(Collection<Map<String, AttributeValue>> keys);

/**
* Put DynamoDb Record.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,19 @@

import static com.formkiq.aws.dynamodb.DbKeys.PK;
import static com.formkiq.aws.dynamodb.DbKeys.SK;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
Expand Down Expand Up @@ -103,6 +108,20 @@ public Map<String, AttributeValue> get(final AttributeValue pk, final AttributeV
.consistentRead(Boolean.TRUE).build()).item();
}

@Override
public List<Map<String, AttributeValue>> getBatch(
final Collection<Map<String, AttributeValue>> keys) {

Map<String, KeysAndAttributes> items =
Map.of(this.tableName, KeysAndAttributes.builder().keys(keys).build());

BatchGetItemResponse response =
this.dbClient.batchGetItem(BatchGetItemRequest.builder().requestItems(items).build());

List<Map<String, AttributeValue>> list = response.responses().get(this.tableName);
return list;
}

@Override
public void putItem(final Map<String, AttributeValue> attributes) {
putItem(this.tableName, attributes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,10 @@ default boolean hasAccess(String method, String path, ApiAuthorizer authorizer)
* @param event {@link ApiGatewayRequestEvent}
* @param authorizer {@link ApiAuthorizer}
* @param awsServices {@link AwsServiceCache}
* @throws Exception Exception
*/
default void beforeDelete(LambdaLogger logger, ApiGatewayRequestEvent event,
ApiAuthorizer authorizer, AwsServiceCache awsServices) {
ApiAuthorizer authorizer, AwsServiceCache awsServices) throws Exception {
// empty
}

Expand All @@ -95,9 +96,10 @@ default void beforeDelete(LambdaLogger logger, ApiGatewayRequestEvent event,
* @param event {@link ApiGatewayRequestEvent}
* @param authorizer {@link ApiAuthorizer}
* @param awsServices {@link AwsServiceCache}
* @throws Exception Exception
*/
default void beforeGet(LambdaLogger logger, ApiGatewayRequestEvent event,
ApiAuthorizer authorizer, AwsServiceCache awsServices) {
ApiAuthorizer authorizer, AwsServiceCache awsServices) throws Exception {
// empty
}

Expand All @@ -108,9 +110,10 @@ default void beforeGet(LambdaLogger logger, ApiGatewayRequestEvent event,
* @param event {@link ApiGatewayRequestEvent}
* @param authorizer {@link ApiAuthorizer}
* @param awsServices {@link AwsServiceCache}
* @throws Exception Exception
*/
default void beforeHead(LambdaLogger logger, ApiGatewayRequestEvent event,
ApiAuthorizer authorizer, AwsServiceCache awsServices) {
ApiAuthorizer authorizer, AwsServiceCache awsServices) throws Exception {
// empty
}

Expand All @@ -121,9 +124,10 @@ default void beforeHead(LambdaLogger logger, ApiGatewayRequestEvent event,
* @param event {@link ApiGatewayRequestEvent}
* @param authorizer {@link ApiAuthorizer}
* @param awsServices {@link AwsServiceCache}
* @throws Exception Exception
*/
default void beforePatch(LambdaLogger logger, ApiGatewayRequestEvent event,
ApiAuthorizer authorizer, AwsServiceCache awsServices) {
ApiAuthorizer authorizer, AwsServiceCache awsServices) throws Exception {
// empty
}

Expand All @@ -134,9 +138,10 @@ default void beforePatch(LambdaLogger logger, ApiGatewayRequestEvent event,
* @param event {@link ApiGatewayRequestEvent}
* @param authorizer {@link ApiAuthorizer}
* @param awsServices {@link AwsServiceCache}
* @throws Exception Exception
*/
default void beforePost(LambdaLogger logger, ApiGatewayRequestEvent event,
ApiAuthorizer authorizer, AwsServiceCache awsServices) {
ApiAuthorizer authorizer, AwsServiceCache awsServices) throws Exception {
// empty
}

Expand All @@ -147,9 +152,10 @@ default void beforePost(LambdaLogger logger, ApiGatewayRequestEvent event,
* @param event {@link ApiGatewayRequestEvent}
* @param authorizer {@link ApiAuthorizer}
* @param awsServices {@link AwsServiceCache}
* @throws Exception Exception
*/
default void beforePut(LambdaLogger logger, ApiGatewayRequestEvent event,
ApiAuthorizer authorizer, AwsServiceCache awsServices) {
ApiAuthorizer authorizer, AwsServiceCache awsServices) throws Exception {
// empty
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import static com.formkiq.aws.dynamodb.SiteIdKeyGenerator.isDefaultSiteId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
Expand All @@ -35,21 +36,15 @@
import com.formkiq.aws.dynamodb.DbKeys;
import com.formkiq.aws.dynamodb.DynamicObject;
import com.formkiq.aws.dynamodb.DynamoDbConnectionBuilder;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import com.formkiq.aws.dynamodb.DynamoDbService;
import com.formkiq.aws.dynamodb.DynamoDbServiceImpl;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;

/** Implementation of the {@link ConfigService}. */
public class ConfigServiceImpl implements ConfigService, DbKeys {

/** {@link DynamoDbClient}. */
private DynamoDbClient dbClient;
/** Documents Table Name. */
private String documentTableName;
/** {@link DynamoDbService}. */
private DynamoDbService db;

/**
* constructor.
Expand All @@ -63,16 +58,14 @@ public ConfigServiceImpl(final DynamoDbConnectionBuilder connection,
throw new IllegalArgumentException("Table name is null");
}

this.dbClient = connection.build();
this.documentTableName = documentsTable;
this.db = new DynamoDbServiceImpl(connection, documentsTable);
}

@Override
public void delete(final String siteId) {
String s = siteId != null ? siteId : DEFAULT_SITE_ID;
Map<String, AttributeValue> keys = keysGeneric(null, PREFIX_CONFIG, s);
this.dbClient.deleteItem(
DeleteItemRequest.builder().tableName(this.documentTableName).key(keys).build());
this.db.deleteItem(keys.get(PK), keys.get(SK));
}

@Override
Expand All @@ -87,24 +80,17 @@ public DynamicObject get(final String siteId) {
keys.add(keysGeneric(null, PREFIX_CONFIG, DEFAULT_SITE_ID));
}

Map<String, KeysAndAttributes> items =
Map.of(this.documentTableName, KeysAndAttributes.builder().keys(keys).build());

BatchGetItemResponse response =
this.dbClient.batchGetItem(BatchGetItemRequest.builder().requestItems(items).build());

AttributeValueToDynamicObject transform = new AttributeValueToDynamicObject();
List<Map<String, AttributeValue>> list = this.db.getBatch(keys);

Optional<Map<String, AttributeValue>> map = Optional.empty();
List<Map<String, AttributeValue>> list = response.responses().get(this.documentTableName);

if (!list.isEmpty()) {
map = list.stream().filter(s -> s.get(SK).s().equals(siteId)).findFirst();
if (map.isEmpty()) {
map = list.stream().filter(s -> s.get(SK).s().equals(DEFAULT_SITE_ID)).findFirst();
}
}

AttributeValueToDynamicObject transform = new AttributeValueToDynamicObject();
return !map.isEmpty() ? transform.apply(map.get()) : new DynamicObject(Map.of());
}

Expand All @@ -117,7 +103,14 @@ public void save(final String siteId, final DynamicObject obj) {
item.put(e.getKey(), AttributeValue.builder().s(e.getValue().toString()).build());
}

this.dbClient
.putItem(PutItemRequest.builder().tableName(this.documentTableName).item(item).build());
if (this.db.exists(item.get(PK), item.get(SK))) {
HashMap<String, AttributeValue> fields = new HashMap<>(item);
fields.remove(PK);
fields.remove(SK);

this.db.updateFields(item.get(PK), item.get(SK), fields);
} else {
this.db.putItem(item);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import com.formkiq.module.ocr.DocumentOcrServiceExtension;
import com.formkiq.plugins.tagschema.DocumentTagSchemaPlugin;
import com.formkiq.plugins.tagschema.DocumentTagSchemaPluginExtension;
import com.formkiq.stacks.api.handler.ConfigsRequestHandler;
import com.formkiq.stacks.api.handler.DocumentIdContentRequestHandler;
import com.formkiq.stacks.api.handler.DocumentIdRequestHandler;
import com.formkiq.stacks.api.handler.DocumentIdUrlRequestHandler;
Expand Down Expand Up @@ -143,6 +144,7 @@ public static void buildUrlMap() {
URL_MAP.put("options", new DocumentsOptionsRequestHandler());
addRequestHandler(new VersionRequestHandler());
addRequestHandler(new SitesRequestHandler());
addRequestHandler(new ConfigsRequestHandler());
addRequestHandler(new DocumentVersionsRequestHandler());
addRequestHandler(new DocumentVersionsKeyRequestHandler());
addRequestHandler(new DocumentTagsRequestHandler());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* MIT License
*
* Copyright (c) 2018 - 2020 FormKiQ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.formkiq.stacks.api.handler;

import static com.formkiq.aws.services.lambda.ApiResponseStatus.SC_OK;
import java.util.Map;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.formkiq.aws.dynamodb.DbKeys;
import com.formkiq.aws.dynamodb.DynamicObject;
import com.formkiq.aws.services.lambda.ApiAuthorizer;
import com.formkiq.aws.services.lambda.ApiGatewayRequestEvent;
import com.formkiq.aws.services.lambda.ApiGatewayRequestEventUtil;
import com.formkiq.aws.services.lambda.ApiGatewayRequestHandler;
import com.formkiq.aws.services.lambda.ApiMapResponse;
import com.formkiq.aws.services.lambda.ApiRequestHandlerResponse;
import com.formkiq.aws.services.lambda.exceptions.BadException;
import com.formkiq.aws.services.lambda.exceptions.UnauthorizedException;
import com.formkiq.aws.services.lambda.services.ConfigService;
import com.formkiq.module.lambdaservices.AwsServiceCache;

/** {@link ApiGatewayRequestHandler} for "/configs". */
public class ConfigsRequestHandler implements ApiGatewayRequestHandler, ApiGatewayRequestEventUtil {

/**
* constructor.
*
*/
public ConfigsRequestHandler() {}

@Override
public void beforeGet(final LambdaLogger logger, final ApiGatewayRequestEvent event,
final ApiAuthorizer authorizer, final AwsServiceCache awsServices) throws Exception {
checkPermissions(authorizer);
}

@Override
public void beforePatch(final LambdaLogger logger, final ApiGatewayRequestEvent event,
final ApiAuthorizer authorizer, final AwsServiceCache awsServices) throws Exception {
checkPermissions(authorizer);
}

private void checkPermissions(final ApiAuthorizer authorizer) throws UnauthorizedException {
if (!authorizer.isUserAdmin()) {
throw new UnauthorizedException("user is unauthorized");
}
}

@Override
public ApiRequestHandlerResponse get(final LambdaLogger logger,
final ApiGatewayRequestEvent event, final ApiAuthorizer authorizer,
final AwsServiceCache awsservice) throws Exception {

String siteId = authorizer.getSiteId();
ConfigService configService = awsservice.getExtension(ConfigService.class);

DynamicObject obj = configService.get(siteId);
obj.remove(DbKeys.PK);
obj.remove(DbKeys.SK);

return new ApiRequestHandlerResponse(SC_OK, new ApiMapResponse(obj));
}

@Override
public String getRequestUrl() {
return "/configs";
}

@SuppressWarnings("unchecked")
@Override
public ApiRequestHandlerResponse patch(final LambdaLogger logger,
final ApiGatewayRequestEvent event, final ApiAuthorizer authorizer,
final AwsServiceCache awsservice) throws Exception {

String siteId = authorizer.getSiteId();

Map<String, String> body = fromBodyToObject(logger, event, Map.class);
if (!body.containsKey("key") && !body.containsKey("value")) {
throw new BadException("'key' and 'value' are required");
}

String key = body.get("key");
String value = body.get("value");
ConfigService configService = awsservice.getExtension(ConfigService.class);
configService.save(siteId, new DynamicObject(Map.of(key, value)));

return new ApiRequestHandlerResponse(SC_OK,
new ApiMapResponse(Map.of("message", "Config saved")));
}
}
Loading

0 comments on commit afbce42

Please sign in to comment.