fix
This commit is contained in:
73
order-events/app/events/stopgap/patch_items.py
Normal file
73
order-events/app/events/stopgap/patch_items.py
Normal file
@@ -0,0 +1,73 @@
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from aws_lambda_powertools import Logger
|
||||
from aws_lambda_powertools.utilities.data_classes import (
|
||||
EventBridgeEvent,
|
||||
event_source,
|
||||
)
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
from layercake.dateutils import now
|
||||
from layercake.dynamodb import (
|
||||
DynamoDBPersistenceLayer,
|
||||
KeyPair,
|
||||
)
|
||||
from sqlite_utils import Database
|
||||
|
||||
from boto3clients import dynamodb_client
|
||||
from config import ORDER_TABLE, SQLITE_DATABASE, SQLITE_TABLE
|
||||
|
||||
sqlite3.register_converter('json', json.loads)
|
||||
|
||||
logger = Logger(__name__)
|
||||
order_layer = DynamoDBPersistenceLayer(ORDER_TABLE, dynamodb_client)
|
||||
|
||||
|
||||
@event_source(data_class=EventBridgeEvent)
|
||||
@logger.inject_lambda_context
|
||||
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
new_image = event.detail['new_image']
|
||||
now_ = now()
|
||||
items = new_image['items']
|
||||
new_items: list[dict] = []
|
||||
|
||||
for item in items:
|
||||
course = _get_course(item['id'])
|
||||
|
||||
new_items.append(
|
||||
item
|
||||
| (
|
||||
{
|
||||
'id': course.get('metadata__betaeducacao_id'),
|
||||
}
|
||||
if course
|
||||
else {}
|
||||
)
|
||||
)
|
||||
|
||||
order_layer.update_item(
|
||||
key=KeyPair(new_image['id'], 'items'),
|
||||
update_expr='SET #items = :items, updated_at = :updated_at',
|
||||
expr_attr_names={'#items': 'items'},
|
||||
expr_attr_values={':items': new_items, ':updated_at': now_},
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class CourseNotFoundError(Exception):
|
||||
def __init__(self, *args):
|
||||
super().__init__('Course not found')
|
||||
|
||||
|
||||
def _get_course(course_id: str) -> dict:
|
||||
with sqlite3.connect(
|
||||
database=SQLITE_DATABASE, detect_types=sqlite3.PARSE_DECLTYPES
|
||||
) as conn:
|
||||
db = Database(conn)
|
||||
rows = db[SQLITE_TABLE].rows_where('id = ?', [course_id])
|
||||
|
||||
for row in rows:
|
||||
return row['json']
|
||||
|
||||
raise CourseNotFoundError
|
||||
Reference in New Issue
Block a user