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
32 changes: 31 additions & 1 deletion src/controllers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
import { PelisCollection, Peli } from "./models";

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

//el constructor esta vacio para que pasen los test
class PelisController {
constructor() {}
model: PelisCollection;
constructor() {
this.model = new PelisCollection();
}
async get(options?: Options): Promise<Peli[]> {
if (options?.id) {
const peli = await this.model.getById(Number(options.id));

return peli ? [peli] : [];
} else if (options?.search) {
return await this.model.search(options.search);
}

return await this.model.getAll();
}
async getOne(options: Options): Promise<Peli | undefined> {
const pelis = await this.get(options);
return pelis[0];
}
async add(peli: Peli) {
return this.model.add(peli);
}
}
export { PelisController };
43 changes: 39 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,50 @@
import minimist from "minimist";
import { Peli, PelisCollection, SearchOptions } from "./models";
import { PelisController, Options } from "./controllers";

function parseaParams(argv) {
const resultado = minimist(argv);
const comando = argv[0];
const args = minimist(argv.slice(1));

return resultado;
let add = null;
let get = null;
let search = null;

if (comando === "add") {
add = {
id: Number(args.id),
title: args.title,
//tags siempre va a devolver array para no generar errores.-
tags: Array.isArray(args.tags) ? args.tags : [args.tags].filter(Boolean),
};
} else if (comando === "get") {
get = { id: Number(argv[1]) || Number(args.id) };
} else if (comando === "search") {
search = {
title: args.title,
tag: args.tag,
};
}

return { add, get, search };
}

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

let result;
if (params.add) {
result = await peliController.add(params.add);
} else if (params.get) {
result = await peliController.get(params.get);
} else if (params.search) {
result = await peliController.get({ search: params.search });
} else {
result = await peliController.get();
}

console.log(params);
console.log(result);
}

main();
61 changes: 57 additions & 4 deletions src/models.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,76 @@
import * as jsonfile from "jsonfile";
// El siguiente import no se usa pero es necesario
import "./pelis.json";
import path from "path";
// de esta forma Typescript se entera que tiene que incluir
// el .json y pasarlo a la carpeta /dist
// si no, solo usandolo desde la libreria jsonfile, no se dá cuenta

// no modificar estas propiedades, agregar todas las que quieras
class Peli {
id: number;
title: string;
tags: string[];
}
export type SearchOptions = { title?: string; tag?: string };

//no tiene propiedades ni constructor para que pase los test
class PelisCollection {
getAll(): Promise<Peli[]> {
return jsonfile.readFile("...laRutaDelArchivo").then(() => {
// la respuesta de la promesa
async getAll(): Promise<Peli[]> {
try {
//cree filePath porque no me corria "./pelis.json"
const filePath = path.resolve(__dirname, "pelis.json");
const data = await jsonfile.readFile(filePath);
return data || [];
} catch (error) {
console.log("Error al buscar el archivo ", error);
return [];
}
}

//busca pelis por id
async getById(id: number): Promise<Peli | undefined> {
const peliBuscada = await this.getAll();
const peliEncontrada = peliBuscada.find((peli) => peli.id === id);
return peliEncontrada;
}

async search(options: SearchOptions): Promise<Peli[]> {
//con esto busca coincidencias si pasas title y tag a la vez.
//y tambien busca si solo le pasas un fragmento del title o un tag
const lista = await this.getAll();

const listraFiltrada = lista.filter((p) => {
const esTitle = options.title
? p.title.toLowerCase().includes(options.title.toLowerCase())
: true;

const esTag = options.tag
? Array.isArray(p.tags) &&
p.tags.some((tag) =>
tag.toLowerCase().includes(options.tag.toLowerCase())
)
: true;
return esTitle && esTag;
});

return listraFiltrada;
}

//agrega una peli en pelis.json
async add(peli: Peli): Promise<boolean> {
const peliExistente = await this.getById(peli.id);
const filePath = path.resolve(__dirname, "pelis.json");

if (peliExistente) {
// si la peli existe devuelve false y no se guarda
return false;
} else {
const currentData = await jsonfile.readFile(filePath);
currentData.push(peli);
await jsonfile.writeFile(filePath, currentData, { spaces: 1 });
return true;
}
}
}

export { PelisCollection, Peli };
33 changes: 32 additions & 1 deletion src/pelis.json
Original file line number Diff line number Diff line change
@@ -1 +1,32 @@
[]
[
{
"id": 1,
"title": "Rocky V",
"tags": ["crack", "superacion", "Genio", "acción"]
},
{
"id": 2,
"title": "Inception",
"tags": ["acción", "sci-fi"]
},
{
"id": 3,
"title": "Titanic",
"tags": ["romance", "drama"]
},
{
"id": 4,
"title": "The Matrix",
"tags": ["acción", "sci-fi"]
},
{
"id": 5,
"title": "The Godfather",
"tags": ["drama", "clásico"]
},
{
"id": 6,
"title": "Hamburguesa Bionica",
"tags": ["action", "classic"]
}
]