Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions src/controllers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,43 @@
import { PelisCollection, Peli } from "./models";
import { PelisCollection, Peli, SearchOptions } from "./models";

type Options = {
id?: number;
search?: {
title?: string;
tag?: string;
};
};

class PelisController {
constructor() {}
model: PelisCollection;

constructor() {
this.model = new PelisCollection();
}

async getOne(options: Options): Promise<Peli | undefined> {
const pelis = await this.get(options);
return pelis[0];
}

async get(options: Options): Promise<Peli[]> {
if (options.id) {
const peli = await this.model.getById(options.id);
return peli ? [peli] : []; // Devuelve un array con la peli o vacío
}
if (options.search) {
return this.model.search(options.search); // Asumiendo que implementaste el método search
}
return this.model.getAll(); // Devuelve todas las pelis
}

add(peli: Peli): Promise<boolean> {
return this.model.add(peli);
}

search(options: SearchOptions): Promise<Peli[]> {
return this.model.search(options);
}
}

export { PelisController };
45 changes: 42 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,54 @@
import minimist from "minimist";
import { PelisCollection } from "./models"; // Asegúrate de importar tu clase

type Search = {
title?: string;
tag?: string;
};

function parseaParams(argv) {
const resultado = minimist(argv);

return resultado;
}

function main() {
async function main() {
const params = parseaParams(process.argv.slice(2));
const pelisCollection = new PelisCollection();

if (params._[0] === "get") {
if (params._.length > 1) {
const id = Number(params._[1]);
const peli = await pelisCollection.getById(id);
console.log(peli ? [peli] : []);
} else {
const pelis = await pelisCollection.getAll();
console.log(pelis);
}
} else if (params._[0] === "search") {
const searchOptions: Search = {};
if (params.title) searchOptions.title = params.title;
if (params.tag) searchOptions.tag = params.tag;

const pelisFiltradas = await pelisCollection.search(searchOptions);
console.log(pelisFiltradas);
} else if (params._[0] === "add") {
const newPeli = {
id: params.id,
title: params.title,
tags: params.tags
? Array.isArray(params.tags)
? params.tags
: [params.tags]
: [],
};

console.log(params);
const result = await pelisCollection.add(newPeli);
console.log(
result ? "Película agregada con éxito." : "Error al agregar la película.",
);
} else {
console.log("Comando no reconocido. Usa 'get', 'search' o 'add'.");
}
}

main();
61 changes: 56 additions & 5 deletions src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ import "./pelis.json";
// el .json y pasarlo a la carpeta /dist
// si no, solo usandolo desde la libreria jsonfile, no se dá cuenta

async function readPelis() {
try {
const pelis = await jsonfile.readFile("src/pelis.json");
console.log(pelis);
} catch (error) {
console.error("Error al leer el archivo:", error);
}
}

//readPelis();

// no modificar estas propiedades, agregar todas las que quieras
class Peli {
id: number;
Expand All @@ -13,11 +24,51 @@ class Peli {
}

class PelisCollection {
getAll(): Promise<Peli[]> {
return jsonfile.readFile("...laRutaDelArchivo").then(() => {
// la respuesta de la promesa
return [];
async getAll(): Promise<Peli[]> {
try {
return await jsonfile.readFile("src/pelis.json");
} catch (error) {
console.error("Error al leer el archivo en getAll:", error);
return []; // Devuelve un array vacío en caso de error
}
}
async getById(id: number): Promise<Peli | undefined> {
try {
const pelis = await this.getAll();
return pelis.find((p) => p.id === id);
} catch (error) {
console.error("Error en getById:", error);
return undefined;
}
}

async search(options: SearchOptions): Promise<Peli[]> {
const pelis = await this.getAll(); // Obtiene todas las películas
return pelis.filter((p) => {
const matchesTitle = options.title
? p.title.includes(options.title)
: true;
const matchesTag = options.tag ? p.tags.includes(options.tag) : true;
return matchesTitle && matchesTag; // Filtra por título y/o tag
});
}

async add(peli: Peli): Promise<boolean> {
return this.getById(peli.id).then((p) => {
if (p) {
return false; // Si la película ya existe, devuelve false
} else {
return this.getAll().then((pelis) => {
pelis.push(peli); // Agrega la nueva película al array
return jsonfile.writeFile("src/pelis.json", pelis).then(() => {
return true; // Devuelve true si se guardó correctamente
});
});
}
});
}
}
export { PelisCollection, Peli };

type SearchOptions = { title?: string; tag?: string };

export { PelisCollection, Peli, SearchOptions };
2 changes: 1 addition & 1 deletion src/pelis.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[]
[{"id":1,"title":"Matrix","tags":["sci-fi","action"]},{"id":2,"title":"Inception","tags":["sci-fi","thriller"]},{"id":3,"title":"The Godfather","tags":["crime","drama"]},{"id":4,"title":"John Wick","tags":["action","suspense"]}]