diff --git a/.gitignore b/.gitignore index 4562b131..76f81824 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ logs test-results.xml .env .idea/ +.npmrc diff --git a/src/index.js b/src/index.js index d0c80753..dfe3e508 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,5 @@ /* - * Copyright 2019 Adobe. All rights reserved. + * Copyright 2023 Adobe. All rights reserved. * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 @@ -13,26 +13,27 @@ import secrets from '@adobe/helix-shared-secrets'; import wrap from '@adobe/helix-shared-wrap'; import { logger } from '@adobe/helix-universal-logger'; import { helixStatus } from '@adobe/helix-status'; -import SQSQueue from './sqs-queue.js'; -import DB from './db.js'; // Assuming the exported content of './db' is default exported -import PSIClient from './psi-client.js'; // Assuming the exported content of './psi-client' is default exported +import DB from './db.js'; +import PSIClient from './psi-client.js'; +import queueWrapper from './queue-wrapper.js'; /** * This is the main function * @param {Request} request the request object (see fetch api) - * @param {UniversalContext} context the context of the universal serverless function + * @param {UniversalContext} context the context of the universal serverle ss function * @returns {Response} a response */ async function run(request, context) { const db = DB({ - region: process.env.REGION, + region: context.env.REGION, }); - const sqsQueue = SQSQueue(); - const { message } = JSON.parse(context.invocation.event.Records[0].body); + const message = JSON.parse(context.invocation.event.Records[0].body); + console.error('###body', context.invocation.event.Records[0].body); + console.error('###message', message); const psiClient = PSIClient({ - apiKey: process.env.PAGESPEED_API_KEY, - baseUrl: process.env.PAGESPEED_API_BASE_URL, + apiKey: context.env.PAGESPEED_API_KEY, + baseUrl: context.env.PAGESPEED_API_BASE_URL, }); const site = { @@ -44,12 +45,13 @@ async function run(request, context) { }; const auditResult = await psiClient.runAudit(`https://${site.domain}/${site.path}`); const auditResultMin = await db.saveAuditIndex(site, auditResult); - await sqsQueue.sendMessage(auditResultMin); + await context.queue.sendAuditResult(auditResultMin); return new Response('SUCCESS'); } export const main = wrap(run) .with(helixStatus) + .with(queueWrapper) .with(logger.trace) .with(logger) .with(secrets); diff --git a/src/util.js b/src/queue-wrapper.js similarity index 55% rename from src/util.js rename to src/queue-wrapper.js index b2c184ad..1565e96f 100644 --- a/src/util.js +++ b/src/queue-wrapper.js @@ -9,25 +9,23 @@ * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ -const log = (level, message, ...args) => { - const timestamp = new Date().toISOString(); - switch (level) { - case 'info': - console.info(`[${timestamp}] INFO: ${message}`, ...args); - break; - case 'error': - console.error(`[${timestamp}] ERROR: ${message}`, ...args); - break; - case 'warn': - console.warn(`[${timestamp}] WARN: ${message}`, ...args); - break; - default: - console.log(`[${timestamp}] ${message}`, ...args); - break; - } -}; +'use strict'; -export { - log, -}; +import SqsQueue from './sqs-queue.js'; + +export default function queueWrapper(func) { + return async (request, context) => { + const { region } = context.runtime; + const queueUrl = process.env.AUDIT_RESULTS_QUEUE_URL; + const { log } = context; + + if (!queueUrl) { + throw new Error('AUDIT_RESULTS_QUEUE_URL env variable is empty/not provided'); + } + + context.queue = new SqsQueue(region, queueUrl, log); + + return func(request, context); + }; +} diff --git a/src/sqs-queue.js b/src/sqs-queue.js index 0278c8b5..2a3ff0d0 100644 --- a/src/sqs-queue.js +++ b/src/sqs-queue.js @@ -9,47 +9,45 @@ * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ -import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'; +import { SendMessageCommand, SQSClient } from '@aws-sdk/client-sqs'; -// Set up the region -const REGION = 'us-east-1'; // change this to your desired region - -// Create SQS service client object -const sqsClient = new SQSClient({ region: REGION }); +/** + * @class SQSQueue class to send audit results to SQS + * @param {string} region - AWS region + * @param {string} queueUrl - SQS queue URL + * @param {object} log - OpenWhisk log object + */ +class SQSQueue { + constructor(region, queueUrl, log) { + if (!this.sqsClient) { + this.sqsClient = new SQSClient({ region }); + log.info(`Creating SQS client in region ${region}`); + } -// Your SQS queue URL -const queueURL = 'https://sqs.us-east-1.amazonaws.com/282898975672/spacecat-audit-results'; + this.queueUrl = queueUrl; + this.log = log; + } -function SQSQueue() { - async function sendMessage(message) { + async sendAuditResult(message) { const body = { message, timestamp: new Date().toISOString(), }; - // Set up the parameters for the send message command const params = { DelaySeconds: 10, MessageBody: JSON.stringify(body), - QueueUrl: queueURL, + QueueUrl: this.queueUrl, }; try { - const data = await sqsClient.send(new SendMessageCommand(params)); - console.log('Success, message sent. MessageID:', data.MessageId); + const data = await this.sqsClient.send(new SendMessageCommand(params)); + this.log.info(`Success, message sent. MessageID: ${data.MessageId}`); } catch (err) { - console.log('Error:', err); + this.log.error(`Error: ${err}`); throw err; } - - return { - statusCode: 200, - body: JSON.stringify({ message: 'SQS message sent!' }), - }; } - return { - sendMessage, - }; } export default SQSQueue;