web: add repo for ingredients

This commit is contained in:
Dmitriy Pleshevskiy 2022-05-27 01:08:25 +03:00
parent f75efb55cf
commit 27a5e2552f
6 changed files with 51 additions and 6 deletions

View File

@ -9,11 +9,11 @@ pub struct Ingredient {
}
impl From<domain::Ingredient> for Ingredient {
fn from(ingr: domain::Ingredient) -> Self {
fn from(app: domain::Ingredient) -> Self {
Self {
key: ingr.key,
lang: ingr.lang.into(),
name: ingr.name,
key: app.key,
lang: app.lang.into(),
name: app.name,
}
}
}

View File

@ -0,0 +1,4 @@
export interface Ingredient {
readonly key: string;
readonly name: string;
}

View File

@ -0,0 +1,29 @@
import { Ingredient } from "../../domain/ingredient/types.ts";
import { RestLang } from "../misc_types.ts";
import { IngredientRepo } from "./types.ts";
export class RestIngredientRepo implements IngredientRepo {
async fetchIngredients(): Promise<Ingredient[]> {
const res = await fetch(
"http://localhost:33333/api/ingredients",
{ headers: { "content-type": "application/json" } },
);
const restIngrs: RestIngredient[] = await res.json();
return restIngrs.map(intoAppIngredient);
}
}
export interface RestIngredient {
readonly key: string;
readonly lang: RestLang;
readonly name: string;
}
export function intoAppIngredient(rest: RestIngredient): Ingredient {
return {
key: rest.key,
name: rest.name,
};
}

View File

@ -0,0 +1,5 @@
import { Ingredient } from "../../domain/ingredient/types.ts";
export interface IngredientRepo {
fetchIngredients(): Promise<Ingredient[]>;
}

4
web/repo/misc_types.ts Normal file
View File

@ -0,0 +1,4 @@
export enum RestLang {
Rus = "Rus",
Eng = "Eng",
}

View File

@ -6,6 +6,7 @@ import * as log from "./log.ts";
import { HomePage } from "./views/home.ts";
import { RecipesPage } from "./views/recipes.ts";
import { IngredientsPage } from "./views/ingredients.ts";
import { RestIngredientRepo } from "./repo/ingredient/rest.ts";
if (import.meta.main) {
await main();
@ -52,6 +53,9 @@ async function handleRequest(req: Request): Promise<Response> {
} else if (ctx.locPath === "/recipes") {
return createHtmlResponse(ren.render(RecipesPage(ctx)));
} else if (ctx.locPath === "/ingredients") {
const repo = new RestIngredientRepo();
const ingredients = await repo.fetchIngredients();
console.log({ ingredients });
return createHtmlResponse(ren.render(IngredientsPage(ctx)));
} else {
return createHtmlResponse(ren.render(E404Page(ctx)), 404);
@ -86,7 +90,6 @@ async function tryCreateFileResponse(urlPath: string): Promise<Response> {
class SkipFile extends Error {}
function createFileResponse(content: string, fileExt: string): Response {
log.debug(fileExt);
return new Response(content, {
headers: getContentTypeHeader(fileExt),
});
@ -115,5 +118,5 @@ function getContentTypeByExt(fileExt: string): string {
}
function getFileExt(filePath: string): string {
return filePath.slice((filePath.lastIndexOf(".") >>> 0) + 1);
return filePath.slice((filePath.lastIndexOf(".") - 1 >>> 0) + 2);
}