style: clean up code formatting and remove trailing whitespace
refactor: reorganize imports and fix type imports
This commit is contained in:
1 parent
d3704602fd
commit
47c04de6fe
232 files changed
+7140
-4798
No files matched your search
@@ -52,9 +52,12 @@ function loadBetterSqlite(): any | null {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return require("better-sqlite3");
|
||||
} catch (error) {
|
||||
secureLogger.warn("better-sqlite3 não está disponível. Importação automática será ignorada.", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
secureLogger.warn(
|
||||
"better-sqlite3 não está disponível. Importação automática será ignorada.",
|
||||
{
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -62,14 +65,19 @@ function loadBetterSqlite(): any | null {
|
||||
function openSQLiteDatabase(Database: any) {
|
||||
const dbPath = path.join(process.cwd(), "data", "tibiawiki.db");
|
||||
if (!fs.existsSync(dbPath)) {
|
||||
secureLogger.warn("Base SQLite não encontrada em data/tibiawiki.db. Importação ignorada.");
|
||||
secureLogger.warn(
|
||||
"Base SQLite não encontrada em data/tibiawiki.db. Importação ignorada.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new Database(dbPath, { readonly: true, fileMustExist: true });
|
||||
} catch (error) {
|
||||
secureLogger.error("Falha ao abrir base SQLite", error instanceof Error ? error.message : error);
|
||||
secureLogger.error(
|
||||
"Falha ao abrir base SQLite",
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -87,7 +95,9 @@ function toNullableDecimal(value: unknown): Prisma.Decimal | null {
|
||||
return new Prisma.Decimal(parsed);
|
||||
}
|
||||
|
||||
function collectMetadata(row: Record<string, unknown>): Record<string, unknown> {
|
||||
function collectMetadata(
|
||||
row: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const metadata: Record<string, unknown> = {};
|
||||
|
||||
for (const field of SQLITE_EXTRA_FIELDS) {
|
||||
@@ -125,7 +135,9 @@ export async function importItemsFromSQLite(): Promise<ImportStats> {
|
||||
|
||||
try {
|
||||
const tables = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
|
||||
)
|
||||
.all() as { name: string }[];
|
||||
|
||||
let processedTables = 0;
|
||||
@@ -136,7 +148,9 @@ export async function importItemsFromSQLite(): Promise<ImportStats> {
|
||||
const batch: Prisma.ItemCreateManyInput[] = [];
|
||||
|
||||
for (const { name: tableName } of tables) {
|
||||
const pragma = db.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{
|
||||
const pragma = db
|
||||
.prepare(`PRAGMA table_info(${tableName})`)
|
||||
.all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
const colNames = new Set(pragma.map((col) => col.name.toLowerCase()));
|
||||
@@ -149,7 +163,10 @@ export async function importItemsFromSQLite(): Promise<ImportStats> {
|
||||
}
|
||||
|
||||
processedTables += 1;
|
||||
const rows = db.prepare(`SELECT * FROM ${tableName}`).all() as Record<string, unknown>[];
|
||||
const rows = db.prepare(`SELECT * FROM ${tableName}`).all() as Record<
|
||||
string,
|
||||
unknown
|
||||
>[];
|
||||
|
||||
for (const row of rows) {
|
||||
processedItems += 1;
|
||||
@@ -169,16 +186,20 @@ export async function importItemsFromSQLite(): Promise<ImportStats> {
|
||||
}
|
||||
|
||||
const imageUrl = (row.image_url ?? row.image ?? null) as string | null;
|
||||
const imageLocalPath = (row.image_local_path ?? row.image_local ?? null) as string | null;
|
||||
const imageLocalPath = (row.image_local_path ??
|
||||
row.image_local ??
|
||||
null) as string | null;
|
||||
const rarity =
|
||||
(row.rarity ?? row.raridade ?? row.rareza ?? null) !== null
|
||||
? String(row.rarity ?? row.raridade ?? row.rareza)
|
||||
: null;
|
||||
const level = toNullableInt(row.lvl ?? row.nivel ?? row.level);
|
||||
const weight = toNullableDecimal(row.peso ?? row.peso_em_oz ?? row.weight);
|
||||
const weight = toNullableDecimal(
|
||||
row.peso ?? row.peso_em_oz ?? row.weight,
|
||||
);
|
||||
const slots = toNullableInt(row.slots ?? row.slot);
|
||||
const skill =
|
||||
row.skill_para_usar ?? row.skill_required ?? row.skill ?? null
|
||||
(row.skill_para_usar ?? row.skill_required ?? row.skill ?? null)
|
||||
? String(row.skill_para_usar ?? row.skill_required ?? row.skill)
|
||||
: null;
|
||||
|
||||
@@ -240,14 +261,18 @@ export async function ensureItemsSeeded(): Promise<ImportStats | null> {
|
||||
const currentCount = await prisma.item.count();
|
||||
if (!seedLogged) {
|
||||
seedLogged = true;
|
||||
secureLogger.info("Verificação da tabela items concluída", { existing: currentCount });
|
||||
secureLogger.info("Verificação da tabela items concluída", {
|
||||
existing: currentCount,
|
||||
});
|
||||
}
|
||||
|
||||
if (currentCount > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
secureLogger.info("Tabela items vazia. Iniciando importação automática a partir do SQLite.");
|
||||
secureLogger.info(
|
||||
"Tabela items vazia. Iniciando importação automática a partir do SQLite.",
|
||||
);
|
||||
try {
|
||||
const stats = await importItemsFromSQLite();
|
||||
secureLogger.info("Importação de itens concluída", stats);
|
||||
@@ -264,4 +289,3 @@ export async function ensureItemsSeeded(): Promise<ImportStats | null> {
|
||||
seedPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
+37
-10
@@ -19,7 +19,13 @@ export interface CategoryTemplate {
|
||||
}
|
||||
|
||||
const BASE_COLUMNS: SQLiteColumnDefinition[] = [
|
||||
{ name: "id", type: "INTEGER", primaryKey: true, notNull: true, editable: false },
|
||||
{
|
||||
name: "id",
|
||||
type: "INTEGER",
|
||||
primaryKey: true,
|
||||
notNull: true,
|
||||
editable: false,
|
||||
},
|
||||
{ name: "nome", type: "TEXT", notNull: true, editable: true },
|
||||
{ name: "image_url", type: "TEXT", editable: true },
|
||||
{ name: "image_local_path", type: "TEXT", editable: true },
|
||||
@@ -50,7 +56,9 @@ function getDatabase(): any {
|
||||
return cachedDatabase;
|
||||
}
|
||||
|
||||
function normalizeColumnType(type: SQLiteColumnType | string): SQLiteColumnType {
|
||||
function normalizeColumnType(
|
||||
type: SQLiteColumnType | string,
|
||||
): SQLiteColumnType {
|
||||
const upper = type.toUpperCase();
|
||||
switch (upper) {
|
||||
case "INTEGER":
|
||||
@@ -82,7 +90,9 @@ function ensureImageDirectory(category: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function mapPragmaColumns(columns: Array<{ name: string; type: string; notnull: number; pk: number }>): SQLiteColumnDefinition[] {
|
||||
function mapPragmaColumns(
|
||||
columns: Array<{ name: string; type: string; notnull: number; pk: number }>,
|
||||
): SQLiteColumnDefinition[] {
|
||||
const mapped = columns.map((column) => {
|
||||
const baseMatch = BASE_COLUMNS.find((base) => base.name === column.name);
|
||||
return {
|
||||
@@ -100,11 +110,15 @@ function mapPragmaColumns(columns: Array<{ name: string; type: string; notnull:
|
||||
export function listCategoryTemplates(): CategoryTemplate[] {
|
||||
const db = getDatabase();
|
||||
const tables = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
|
||||
)
|
||||
.all() as Array<{ name: string }>;
|
||||
|
||||
return tables.map((table) => {
|
||||
const pragma = db.prepare(`PRAGMA table_info(${table.name})`).all() as Array<{
|
||||
const pragma = db
|
||||
.prepare(`PRAGMA table_info(${table.name})`)
|
||||
.all() as Array<{
|
||||
name: string;
|
||||
type: string;
|
||||
notnull: number;
|
||||
@@ -124,7 +138,9 @@ export function listCategoryTemplates(): CategoryTemplate[] {
|
||||
|
||||
function validateCategoryName(name: string) {
|
||||
if (!/^[a-z0-9_]+$/i.test(name)) {
|
||||
throw new Error("Nome da categoria deve conter apenas letras, números ou sublinhado.");
|
||||
throw new Error(
|
||||
"Nome da categoria deve conter apenas letras, números ou sublinhado.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +149,9 @@ export interface CreateCategoryInput {
|
||||
columns?: SQLiteColumnDefinition[];
|
||||
}
|
||||
|
||||
export function createCategoryTemplate(input: CreateCategoryInput): CategoryTemplate {
|
||||
export function createCategoryTemplate(
|
||||
input: CreateCategoryInput,
|
||||
): CategoryTemplate {
|
||||
const db = getDatabase();
|
||||
const name = input.name.trim().toLowerCase();
|
||||
validateCategoryName(name);
|
||||
@@ -184,7 +202,9 @@ export interface AddColumnInput {
|
||||
column: SQLiteColumnDefinition;
|
||||
}
|
||||
|
||||
export function addColumnToCategory(input: AddColumnInput): SQLiteColumnDefinition {
|
||||
export function addColumnToCategory(
|
||||
input: AddColumnInput,
|
||||
): SQLiteColumnDefinition {
|
||||
const db = getDatabase();
|
||||
const name = input.category.trim().toLowerCase();
|
||||
validateCategoryName(name);
|
||||
@@ -262,7 +282,11 @@ export function insertCategoryItem(input: UpsertItemInput): number {
|
||||
return Number(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
export function updateCategoryItem(category: string, id: number, data: Record<string, unknown>) {
|
||||
export function updateCategoryItem(
|
||||
category: string,
|
||||
id: number,
|
||||
data: Record<string, unknown>,
|
||||
) {
|
||||
const db = getDatabase();
|
||||
const normalized = category.trim().toLowerCase();
|
||||
validateCategoryName(normalized);
|
||||
@@ -282,7 +306,10 @@ export function updateCategoryItem(category: string, id: number, data: Record<st
|
||||
db.prepare(sql).run(...values, id);
|
||||
}
|
||||
|
||||
export function getCategoryItem(category: string, id: number): Record<string, unknown> | null {
|
||||
export function getCategoryItem(
|
||||
category: string,
|
||||
id: number,
|
||||
): Record<string, unknown> | null {
|
||||
const db = getDatabase();
|
||||
const normalized = category.trim().toLowerCase();
|
||||
validateCategoryName(normalized);
|
||||
|
||||
Reference in new issue
Block a user