Skip to content

Commit

Permalink
feat: update according to code review
Browse files Browse the repository at this point in the history
  • Loading branch information
alinarublea committed Oct 20, 2023
1 parent 3271e0f commit 930c617
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 109 deletions.
23 changes: 8 additions & 15 deletions src/db-wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,17 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import createDynamoDBService from './db.js';
import serviceWrap from './service-wrap.js';
import DB from './db.js';

export default function dynamoDBWrapper(func) {
return async (...args) => {
let params = {};
let context = {};
[params, context = {}] = args;
const region = context.env.AWS_REGION;
return async (request, context) => {
const { region } = context.runtime;
if (!region) {
throw Error('Please define region in secrets');
throw Error('Region is undefined');
}
serviceWrap(
params,
context,
'__ow_dynamodb',
createDynamoDBService,
);
return func(...args);
if (!context.dynamoStorage) {
context.dynamoStorage = new DB(context);
}
return func(request, context);
};
}
51 changes: 24 additions & 27 deletions src/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
*/
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, GetItemCommand, PutCommand } from '@aws-sdk/lib-dynamodb';
import { log } from './util.js';

const TABLE_SITES = 'spacecat-site';
const TABLE_AUDITS = 'spacecat-audit-index';

class DB {
export default class DB {
constructor(context) {
this.client = new DynamoDBClient({ region: context.region });
this.client = new DynamoDBClient({ region: context.runtime.region });
this.logger = context.log;
this.docClient = DynamoDBDocumentClient.from(this.client);
}

Expand All @@ -35,19 +35,20 @@ class DB {
});
await this.docClient.send(command);
} catch (error) {
log('error', 'Error saving record: ', error);
this.logger('error', 'Error saving record: ', error);
}
}

/**
* Saves an audit to the DynamoDB.
* @param {object} site - Site object containing details of the audited site.
* @param {object} audit - Audit object containing the type and result of the audit.
* @returns {Promise<void>} Resolves once audit is saved.
*/
* Saves an audit to the DynamoDB.
* @param {object} site - Site object containing details of the audited site.
* @param {object} audit - Audit object containing the type and result of the audit.
* @returns {Promise<void>} Resolves once audit is saved.
*/
async saveAuditIndex(site, audit) {
const now = new Date().toISOString();
const uuid = Date.now().toString();
const uuid = Date.now()
.toString();

const newAudit = {
id: uuid,
Expand Down Expand Up @@ -80,16 +81,16 @@ class DB {
},
],
};
log('info', `Audit for domain ${site.domain} saved successfully at ${now}`);
this.logger('info', `Audit for domain ${site.domain} saved successfully at ${now}`);
await this.saveRecord(newAudit, TABLE_AUDITS);
return Promise.resolve(newAudit);
}

/**
* Save an error that occurred during a Lighthouse audit to the DynamoDB.
* @param {object} site - site audited.
* @param {Error} error - The error that occurred during the audit.
*/
* Save an error that occurred during a Lighthouse audit to the DynamoDB.
* @param {object} site - site audited.
* @param {Error} error - The error that occurred during the audit.
*/
async saveAuditError(site, error) {
const now = new Date().toISOString();
const newAudit = {
Expand All @@ -103,11 +104,11 @@ class DB {
}

/**
* Fetches a site by its ID and gets its latest audit.
* @param {string} domain - The domain of the site to fetch.
* @param {string} path - The path of the site to fetch.
* @returns {Promise<object>} Site document with its latest audit.
*/
* Fetches a site by its ID and gets its latest audit.
* @param {string} domain - The domain of the site to fetch.
* @param {string} path - The path of the site to fetch.
* @returns {Promise<object>} Site document with its latest audit.
*/
async getSite(domain, path) {
const commandParams = {
TableName: TABLE_SITES, // Replace with your table name
Expand All @@ -122,19 +123,15 @@ class DB {
const response = await this.client.send(command);
const item = response.Item;
if (item) {
log('info', `Item retrieved successfully: ${item}`);
this.logger('info', `Item retrieved successfully: ${item}`);
return item;
} else {
log('info', 'Item not found.');
this.logger('info', 'Item not found.');
return null;
}
} catch (error) {
log('error', `Error ${error}`);
this.logger('error', `Error ${error}`);
throw error;
}
}
}

export default function createDynamoDBService(context) {
return new DB(context);
}
7 changes: 1 addition & 6 deletions src/psi-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
* governing permissions and limitations under the License.
*/
import axios from 'axios';
import { log } from './util.js';

function PSIClient(config) {
const AUDIT_TYPE = 'PSI';
Expand Down Expand Up @@ -136,6 +135,7 @@ function PSIClient(config) {
* @returns {Promise<object>} The processed PageSpeed Insights audit data.
*/
const performPSICheck = async (domain, strategy) => {
// eslint-disable-next-line no-useless-catch
try {
const apiURL = getPSIApiUrl(domain, strategy);
const { data: lhs } = await axios.get(apiURL);
Expand All @@ -144,7 +144,6 @@ function PSIClient(config) {

return processLighthouseResult(lighthouseResult);
} catch (e) {
log('error', `Error happened during PSI check: ${e}`);
throw e;
}
};
Expand All @@ -153,12 +152,8 @@ function PSIClient(config) {
const auditResults = {};

for (const strategy of PSI_STRATEGIES) {
const strategyStartTime = process.hrtime();
// eslint-disable-next-line no-await-in-loop
const psiResult = await performPSICheck(domain, strategy);
const strategyEndTime = process.hrtime(strategyStartTime);
const strategyElapsedTime = (strategyEndTime[0] + strategyEndTime[1] / 1e9).toFixed(2);
log('info', `Audited ${domain} for ${strategy} strategy in ${strategyElapsedTime} seconds`);

auditResults[strategy] = psiResult;
}
Expand Down
24 changes: 0 additions & 24 deletions src/service-wrap.js

This file was deleted.

7 changes: 3 additions & 4 deletions src/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import { S3 } from "@aws-sdk/client-s3";
import { log } from 'util';
import { S3 } from '@aws-sdk/client-s3';

function storage(config) {
const s3 = new S3({ region: config.region });
Expand All @@ -22,11 +21,11 @@ function storage(config) {
ContentType: 'application/json',
};

// eslint-disable-next-line no-useless-catch
try {
log('info', `Data saved to S3 with key: ${key}`);
await s3.putObject(params);
} catch (error) {
log('error', 'Error saving data to S3: ', error);
throw error;
}
}
}
Expand Down
33 changes: 0 additions & 33 deletions src/util.js

This file was deleted.

0 comments on commit 930c617

Please sign in to comment.