All files / src/functions process.entities.ts

100% Statements 41/41
100% Branches 13/13
100% Functions 11/11
100% Lines 33/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58    2x 2x   2x 2x   2x 18x 18x 18x 17x     2x 18x 13x   11x     2x 18x   14x   14x 34x 34x 34x             34x 34x   14x 22x 22x 18x     13x     2x 7x 7x 7x 6x     2x  
'use strict';
 
import * as fs from 'node:fs';
import * as path from 'node:path';
 
import {endsWith, find, isString} from 'lodash';
import {listSubfoldersByName, type ItemStat} from '@owservable/folders';
 
const _processFile = (folder: string, file: string, entities: any[]): void => {
	const fullPath: string = path.join(folder, file);
	const entity: any = require(fullPath).default;
	if (!entity) throw new Error(`Entity not found in ${folder}/${file}`);
	entities.push(entity);
};
 
const _isExcluded = (folder: string, exclude: string | string[]): boolean => {
	if (!exclude) return false;
	return isString(exclude) //
		? endsWith(folder, exclude) //
		: !!find(exclude, (e: string) => endsWith(folder, e));
};
 
const _processSqliteEntities = (folder: string, entities: any[], exclude?: string | string[]): void => {
	if (_isExcluded(folder, exclude)) return;
 
	const subfolderNames: string[] = fs.readdirSync(folder);
 
	const itemStats: ItemStat[] = subfolderNames.map((fileName: string): ItemStat => {
		const fullPath: string = path.join(folder, fileName);
		const stat: fs.Stats = fs.lstatSync(fullPath);
		return {
			name: fileName,
			fullPath,
			isDirectory: stat.isDirectory()
		};
	});
 
	const files: ItemStat[] = itemStats.filter((item: ItemStat): boolean => !item.isDirectory);
	const folders: ItemStat[] = itemStats.filter((item: ItemStat): boolean => item.isDirectory);
 
	files.forEach((file: ItemStat): void => {
		const ext: string = path.extname(file.name);
		if (ext !== '.ts' && ext !== '.js') return;
		_processFile(folder, file.name, entities);
	});
 
	folders.forEach((subFolder: ItemStat): void => _processSqliteEntities(subFolder.fullPath, entities, exclude));
};
 
const processSqliteEntities = (root: string, name: string = 'entities', exclude?: string | string[]): any[] => {
	const entities: any[] = [];
	const folders: string[] = listSubfoldersByName(root, name);
	folders.forEach((folder: string): void => _processSqliteEntities(folder, entities, exclude));
	return entities;
};
 
export default processSqliteEntities;