Files
Playwright-A11y-Dashboard/models/SiteModel.js
2025-05-26 08:30:15 -05:00

105 lines
2.7 KiB
JavaScript

/**
* Model for managing sites table in the database.
*/
const { supabase } = require('../auth');
const { isValidDomain } = require('../helpers/utils');
class SiteModel {
static tableName = 'sites';
/**
* Inserts a new site into the database.
*
* @param {string} name - The name of the site.
* @param {string} domainName - The domain name of the site.
*
* @returns {Promise<Object>} - The result of the insert operation.
*/
async insert(domainName) {
// validate inputs
if (!domainName) {
throw new Error('Name and domain name are required to insert a site.');
}
// validate domain name format
if (!isValidDomain(domainName)) {
throw new Error('Invalid domain name format.');
}
// check if the domain name already exists
if (await this.getByDomainName(domainName).then(data => data.length !== 0)) {
throw new Error('Domain name already exists.');
}
const { data, error } = await supabase.from(SiteModel.tableName).insert({
domain_name: domainName,
}).select();
if (error) {
console.error('Error inserting site:', error);
throw error;
}
return data;
}
/**
* Retrieves all sites from the database.
*
* @returns {Promise<Array>} - An array of site objects.
*/
async getAll() {
const { data, error } = await supabase.from(SiteModel.tableName).select('*');
if (error) {
console.error('Error fetching sites:', error);
throw error;
}
data.reverse(); // Reverse the order to show the most recent sites first
return data;
}
/**
* Retrieves a site by its ID.
*
* @param {number} id - The ID of the site.
*
* @returns {Promise<Object>} - The site object.
*/
async getById(id) {
const { data, error } = await supabase.from(SiteModel.tableName).select('*').eq('id', id).single();
if (error) {
console.error('Error fetching site by ID:', error);
throw error;
}
return data;
}
/**
* Retrieves a site by its domain name.
*
* @param {string} domainName - The domain name of the site.
*
* @returns {Promise<Object>} - The site object.
*/
async getByDomainName(domainName) {
const { data, error } = await supabase.from(SiteModel.tableName).select('*').eq('domain_name', domainName);
if (error) {
console.error('Error fetching site by domain name:', error);
throw error;
}
return data;
}
}
module.exports = SiteModel;