[英]What do I need to add to my Javascript to be able to show the hit counter from my DynamoDB table and API Gateway?
I want to be able to retrieve the hit counter from my DynamoDB table.我希望能够从我的 DynamoDB 表中检索命中计数器。 I have an API Gateway, Lambda, and DynamoDB table all working with each other correctly.
我有一个 API 网关、Lambda 和 DynamoDB 表都可以正常工作。 So far the code I have hits the API, triggering a count in the dynamo table, however the count on my site stays at 0. I'm very new to Javascript so I was hoping I could get some guidance for this.
到目前为止,我已经点击 API 的代码,触发了发电机表中的计数,但是我网站上的计数保持在 0。我对 Javascript 很陌生,所以我希望我能得到一些指导。 Here's the code I have so far:
这是我到目前为止的代码:
const countEl = document.getElementById('count');
updateVisitCount();
function updateVisitCount() {
fetch('https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/prod/')
.then(res => res.json())
.then(res => {
countEl.innerHTML = res.value;
})
}
My Lambda Function:我的 Lambda Function:
import json
import os
import boto3
ddb = boto3.resource('dynamodb')
table = ddb.Table(os.environ['HITS_TABLE_NAME'])
_lambda = boto3.client('lambda')
def handler(event, context):
print('request: {}'.format(json.dumps(event)))
table.update_item(
Key={'path': event['path']},
UpdateExpression='ADD hits :incr',
ExpressionAttributeValues={':incr': 1}
)
resp = _lambda.invoke(
FunctionName=os.environ['DOWNSTREAM_FUNCTION_NAME'],
Payload=json.dumps(event),
)
body = resp['Payload'].read()
print('downstream response: {}'.format(body))
return json.loads(body)
Thanks for your help!谢谢你的帮助!
how often is the data on dynamodb updated? dynamodb 上的数据多久更新一次?
the easy workaround is calling updateVisitCount()
every N seconds.简单的解决方法是每 N 秒调用
updateVisitCount()
。
You can try with this code.您可以尝试使用此代码。 It will update value every 5 seconds
它将每 5 秒更新一次值
const countEl = document.getElementById('count');
function updateVisitCount() {
fetch('https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/prod/')
.then(res => res.json())
.then(res => {
countEl.innerHTML = res.value;
})
}
setInterval(updateVisitCount, 5000)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.