Skip to content

Commit

Permalink
get jewellery roughly working
Browse files Browse the repository at this point in the history
  • Loading branch information
jaskaransarkaria committed Jan 31, 2021
1 parent 9e0be56 commit 828dd63
Show file tree
Hide file tree
Showing 9 changed files with 128 additions and 42 deletions.
2 changes: 1 addition & 1 deletion .routify/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ module.exports = {
"svx",
"md"
],
"started": "2021-01-30T20:58:04.111Z"
"started": "2021-01-31T12:48:46.113Z"
}
4 changes: 2 additions & 2 deletions .routify/routes.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@

/**
* @roxi/routify 2.7.3
* File generated Sat Jan 30 2021 20:58:05 GMT+0000 (Greenwich Mean Time)
* File generated Sun Jan 31 2021 12:48:47 GMT+0000 (Greenwich Mean Time)
*/

export const __version = "2.7.3"
export const __timestamp = "2021-01-30T20:58:05.710Z"
export const __timestamp = "2021-01-31T12:48:47.585Z"

//buildRoutes
import { buildClientTree } from "@roxi/routify/runtime/buildRoutes"
Expand Down
3 changes: 2 additions & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ export default {
'process.env.SERVER_URL': production ?
JSON.stringify('https://server.enki.jobspeed.uk') :
JSON.stringify('http://localhost:8080'),
'process.env.STRIPE_KEY': JSON.stringify('pk_test_51HpvnTAk37gvJ51oYwywMtrDcDlL6FXuVY0aQ1EYEJUiw9MG70UElEMhhazqhhafUOslK1IugHRApQ7GWNUcnqT400dJ4HWjbp')
'process.env.STRIPE_KEY': JSON.stringify('pk_test_51HpvnTAk37gvJ51oYwywMtrDcDlL6FXuVY0aQ1EYEJUiw9MG70UElEMhhazqhhafUOslK1IugHRApQ7GWNUcnqT400dJ4HWjbp'),
'process.env.JEWELLERY_CATEGORY_ID': JSON.stringify('1875996')
}),

// In dev mode, call `npm run start` once
Expand Down
18 changes: 11 additions & 7 deletions src/components/ProductView/ProductView.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { onMount } from 'svelte';
import AddToBasket from '../AddToBasket/AddToBasket.svelte';
import { retrieveStateFn } from '../../libs/requests';
import type { GetFn } from '../../libs/requests';
interface Product {
Expand All @@ -16,17 +17,20 @@
let productArr: readonly Product[] = [];
const getProducts: GetFn<Product> = (url: string): Promise<ReadonlyArray<Product>> =>
fetch(url).then((res) => res.json());
const getProducts: GetFn<Product> = (
url: string
): Promise<ReadonlyArray<Product>> => fetch(url).then((res) => res.json());
onMount(async () => {
const refreshProducts = async (id: string) => {
const result = await retrieveStateFn(
process.env.SERVER_URL as string,
categoryId,
`${process.env.SERVER_URL}/products-by-category?id=${id}`,
getProducts
)()();
productArr = result['_tag'] === 'Right' ? result.right : [];
});
productArr = result['_tag'] === 'Right' ? result.right as Product[] : [];
}
onMount(async () => await refreshProducts(categoryId));
$: refreshProducts(categoryId)
</script>

<style>
Expand Down
3 changes: 3 additions & 0 deletions src/components/SearchJewellery/SearchJewellery.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<script lang="ts">
import { jewellery } from '../../stores/jewellery';
import { onMount } from 'svelte';
let searchValue: string = '';
let results: any[] = [];
const fetchJewelleryProducts = async () => {
Expand All @@ -10,6 +12,7 @@
`${process.env.SERVER_URL}/jewellery-products`
);
const parsedResult = await response.json();
console.log("fetched", parsedResult)
return parsedResult;
} catch (err) {
console.error('fetching jewellery products failed', err);
Expand Down
18 changes: 10 additions & 8 deletions src/libs/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,26 @@ export const fetchCategories = async () => {
};

export const retrieveStateFn = <T>(
serverUrl: string,
catId: string,
getState: GetFn<T>,
) => (): () => Promise<E.Either<Error, ReadonlyArray<T>>> => {
url: string,
getState: GetFn<T>
) => (): (() => Promise<E.Either<Error, T | ReadonlyArray<T>>>) => {
// fetch all the products in a specific category
const get = (url: string): TE.TaskEither<Error, ReadonlyArray<T>> =>
const get = (url: string): TE.TaskEither<Error, T | ReadonlyArray<T>> =>
// TaskEither is from asynchronous operations that can fail
TE.tryCatch(
() => getState(url),
() => new Error(`Error fetching products`)
);

return pipe(
`${serverUrl}/products-by-category?id=${catId}`,
url,
get,
TE.chain((result) => TE.of(result))
);
};
export interface GetFn <T>{
(url: string): Promise<ReadonlyArray<T>>;
export interface GetFn<T> {
(url: string): Promise<T | ReadonlyArray<T>>;
}


export const getCategoryId: GetFn<string> = (url: string): Promise<string> => fetch(url).then((res) => res.json());
44 changes: 23 additions & 21 deletions src/pages/online-shop/[category].svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,47 @@
import { categories } from '../../stores/categories';
import ProductView from '../../components/ProductView/ProductView.svelte';
import SearchJewellery from '../../components/SearchJewellery/SearchJewellery.svelte';
import { retrieveStateFn, getCategoryId } from '../../libs/requests';
import type { Category } from '../../stores/categories'
export let category: string;
const fetchCategoryById = async (id: string) => {
const response = await fetch(`${process.env.SERVER_URL}/category?id=${id}`);
const parsedResult = JSON.parse(await response.json());
return parsedResult;
};
onMount(async () => {
if (!$categories.hasOwnProperty('Id')) {
try {
const data = await fetchCategoryById(category);
categories.set(data);
} catch (err) {
console.error('fetching category failed', err);
}
}
const JEWELLERY_CATEGORY = process.env.JEWELLERY_CATEGORY_ID
onMount(async () => {
// This prevents the app for fetching the categories if it has already pulled them
// but will pull them if visiting the link directly
// if (!$categories.hasOwnProperty('Id') || $categories.Id === '') {
// const result = await retrieveStateFn(`${process.env.SERVER_URL}/category?id=${category}`, getCategoryId)()()
// const data: Category = result['_tag'] === 'Right' ? JSON.parse(result.right as string) : { Id: '', Name: '', Children: []}
// categories.set(data);
// }
const result = await retrieveStateFn(`${process.env.SERVER_URL}/category?id=${category}`, getCategoryId)()()
const data: Category = result['_tag'] === 'Right' ? JSON.parse(result.right as string) : { Id: '', Name: '', Children: []}
categories.set(data);
});
</script>

<h1>PARAMS {$params.category}</h1>
<h1>{category}</h1>

{#if category === '1821413'}
{#if category === JEWELLERY_CATEGORY}
<SearchJewellery />
{/if}

{#if $categories.hasOwnProperty('Id')}
{#if $categories.Id !== JEWELLERY_CATEGORY}
<h1>{$categories.Id}</h1>
<h1>{$categories.Name}</h1>
{#if $categories.Children.length > 0}
{#each $categories.Children as category}
{#each $categories.Children as cat}
<button
on:click={() => {
categories.set(category);
$goto(`./${$params.category}/${category.Id}`);
// categories.set(cat);
$goto(`./${$params.category}/${cat.Id}`);
}}>
{category.Name}
{cat.Name}
</button>
{/each}
{:else}
Expand Down
65 changes: 64 additions & 1 deletion src/pages/online-shop/[subCategory]/[subCategory].svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,73 @@
<script lang="ts">
import { params } from '@roxi/routify';
import { onMount } from 'svelte';
import ProductView from '../../../components/ProductView/ProductView.svelte';
import { categories } from '../../../stores/categories';
import { retrieveStateFn, getCategoryId } from '../../../libs/requests';
import type { Category } from '../../../stores/categories';
export let subCategory: string;
let showProduct = false;
let productToShow: string;
onMount(async () => {
// This prevents the app for fetching the categories if it has already pulled them
// but will pull them if visiting the link directly
// if (!$categories.hasOwnProperty('Id') || $categories.Id === '') {
// const result = await retrieveStateFn(
// `${process.env.SERVER_URL}/category?id=${subCategory}`,
// getCategoryId
// )()();
// const data: Category =
// result['_tag'] === 'Right'
// ? JSON.parse(result.right as string)
// : { Id: '', Name: '', Children: [] };
// categories.set(data);
// } else {
// // show category children OR show productview
// const matchedCat = [...$categories.Children];
// categories.set(matchedCat.find(obj => obj.Id.toString() === subCategory)!)
// }
const result = await retrieveStateFn(
`${process.env.SERVER_URL}/category?id=${subCategory}`,
getCategoryId
)()();
const data: Category =
result['_tag'] === 'Right'
? JSON.parse(result.right as string)
: { Id: '', Name: '', Children: [] };
categories.set(data);
});
</script>

<h1>{JSON.stringify($params.subCategory)}</h1>
<h1>{subCategory}</h1>
<ProductView categoryId={subCategory} />

<!-- <SearchJewellery /> -->

{#if $categories.hasOwnProperty('Id') || $categories.Id === ''}
<h1>{$categories.Id}</h1>
<h1>{$categories.Name}</h1>
{#if $categories.Children.length > 0}
{#each $categories.Children as cat}
<button
on:click={() => {
showProduct = true
console.log(cat.Id)
productToShow = cat.Id
console.log(productToShow)
}}>
{cat.Name}
</button>
{/each}
{:else}
<ProductView categoryId={subCategory} />
{/if}

{#if showProduct}
{console.log("product to show:", productToShow)}
<ProductView categoryId={productToShow} />
{/if}
{/if}
13 changes: 12 additions & 1 deletion src/stores/categories.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
import { writable } from 'svelte/store';

export const categories = writable({});
export interface Category {
Id: string;
Name: string;
Children: Category[];
}


export const categories = writable<Category>({
Id: '',
Name: '',
Children: []
});

0 comments on commit 828dd63

Please sign in to comment.