@springmicro/cart 0.3.0 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils/api.ts CHANGED
@@ -1,67 +1,67 @@
1
- function postInit(body: any): RequestInit {
2
- const init: RequestInit = {
3
- method: "POST",
4
- headers: { "Content-Type": "application/json" },
5
- };
6
- if (typeof body === "string") {
7
- return { ...init, body };
8
- }
9
- return { ...init, body: JSON.stringify(body) };
10
- }
11
-
12
- async function dataOrResponse(res: Response) {
13
- if (res.status === 200) {
14
- return await res.json();
15
- } else {
16
- return res;
17
- }
18
- }
19
-
20
- async function dataOr404(res: Response) {
21
- if (res.status === 200) {
22
- return await res.json();
23
- } else {
24
- return new Response(null, { status: 404 });
25
- }
26
- }
27
-
28
- export async function getOrder(
29
- apiBaseUrl: string,
30
- id: string,
31
- orderReference: string
32
- ) {
33
- const res = await fetch(
34
- `${apiBaseUrl}/api/ecommerce/orders/${id}/reference/${orderReference}`
35
- );
36
- return await dataOr404(res);
37
- }
38
-
39
- export async function getInvoice(
40
- apiBaseUrl: string,
41
- id: string,
42
- orderReference: string
43
- ) {
44
- const res = await fetch(
45
- `${apiBaseUrl}/api/ecommerce/invoice/${id}/reference/${orderReference}`
46
- );
47
- return await dataOr404(res);
48
- }
49
-
50
- export async function postCheckout(
51
- apiBaseUrl: string,
52
- id: string,
53
- orderReference: string,
54
- body: object,
55
- paymentProvider: string,
56
- invoiceId?: string
57
- ): Promise<object | Response> {
58
- const url = new URL(
59
- `${apiBaseUrl}/api/ecommerce/checkout/${id}/${orderReference}`
60
- );
61
- url.searchParams.set("payment_provider", paymentProvider);
62
- if (invoiceId !== undefined) {
63
- url.searchParams.set("invoice_id", invoiceId);
64
- }
65
- const res = await fetch(url, postInit(body));
66
- return await dataOrResponse(res);
67
- }
1
+ function postInit(body: any): RequestInit {
2
+ const init: RequestInit = {
3
+ method: "POST",
4
+ headers: { "Content-Type": "application/json" },
5
+ };
6
+ if (typeof body === "string") {
7
+ return { ...init, body };
8
+ }
9
+ return { ...init, body: JSON.stringify(body) };
10
+ }
11
+
12
+ async function dataOrResponse(res: Response) {
13
+ if (res.status === 200) {
14
+ return await res.json();
15
+ } else {
16
+ return res;
17
+ }
18
+ }
19
+
20
+ async function dataOr404(res: Response) {
21
+ if (res.status === 200) {
22
+ return await res.json();
23
+ } else {
24
+ return new Response(null, { status: 404 });
25
+ }
26
+ }
27
+
28
+ export async function getOrder(
29
+ apiBaseUrl: string,
30
+ id: string,
31
+ orderReference: string
32
+ ) {
33
+ const res = await fetch(
34
+ `${apiBaseUrl}/api/ecommerce/orders/${id}/reference/${orderReference}`
35
+ );
36
+ return await dataOr404(res);
37
+ }
38
+
39
+ export async function getInvoice(
40
+ apiBaseUrl: string,
41
+ id: string,
42
+ orderReference: string
43
+ ) {
44
+ const res = await fetch(
45
+ `${apiBaseUrl}/api/ecommerce/invoice/${id}/reference/${orderReference}`
46
+ );
47
+ return await dataOr404(res);
48
+ }
49
+
50
+ export async function postCheckout(
51
+ apiBaseUrl: string,
52
+ id: string,
53
+ orderReference: string,
54
+ body: object,
55
+ paymentProvider: string,
56
+ invoiceId?: string
57
+ ): Promise<object | Response> {
58
+ const url = new URL(
59
+ `${apiBaseUrl}/api/ecommerce/checkout/${id}/${orderReference}`
60
+ );
61
+ url.searchParams.set("payment_provider", paymentProvider);
62
+ if (invoiceId !== undefined) {
63
+ url.searchParams.set("invoice_id", invoiceId);
64
+ }
65
+ const res = await fetch(url, postInit(body));
66
+ return await dataOrResponse(res);
67
+ }
@@ -1,50 +1,50 @@
1
- import { defaultCartValue } from ".";
2
- import { ApiCartResponse, Cart } from "../types";
3
- import { Storage } from "unstorage";
4
-
5
- export function cartAuthHandler(
6
- cartState: [Cart, React.Dispatch<React.SetStateAction<Cart>>],
7
- storage: {
8
- api: Storage<any>;
9
- local: Storage<any>;
10
- } | null,
11
- userId: number | string | undefined,
12
- prevUserId: number | string | undefined
13
- ) {
14
- const [cart, setCart] = cartState;
15
- if (storage === null) return () => {}; // storage can be null.
16
-
17
- if (userId === prevUserId) return;
18
-
19
- if (userId === undefined) {
20
- // logout
21
- setCart(defaultCartValue);
22
- return;
23
- }
24
-
25
- // login
26
- if (cart.items.length > 0) {
27
- setCart((c) => ({
28
- ...c,
29
- authentication: {
30
- loggedIn: true,
31
- user_id: userId,
32
- },
33
- }));
34
- return;
35
- }
36
- storage.api
37
- .getItem(`${userId}`)
38
- .then((c2: ApiCartResponse) => {
39
- if (!c2) return;
40
-
41
- setCart({
42
- items: JSON.parse(c2.cart),
43
- authentication: {
44
- loggedIn: true,
45
- user_id: c2.user_id,
46
- },
47
- });
48
- })
49
- .catch(() => {});
50
- }
1
+ import { defaultCartValue } from ".";
2
+ import { ApiCartResponse, Cart } from "../types";
3
+ import { Storage } from "unstorage";
4
+
5
+ export function cartAuthHandler(
6
+ cartState: [Cart, React.Dispatch<React.SetStateAction<Cart>>],
7
+ storage: {
8
+ api: Storage<any>;
9
+ local: Storage<any>;
10
+ } | null,
11
+ userId: number | string | undefined,
12
+ prevUserId: number | string | undefined
13
+ ) {
14
+ const [cart, setCart] = cartState;
15
+ if (storage === null) return () => {}; // storage can be null.
16
+
17
+ if (userId === prevUserId) return;
18
+
19
+ if (userId === undefined) {
20
+ // logout
21
+ setCart(defaultCartValue);
22
+ return;
23
+ }
24
+
25
+ // login
26
+ if (cart.items.length > 0) {
27
+ setCart((c) => ({
28
+ ...c,
29
+ authentication: {
30
+ loggedIn: true,
31
+ user_id: userId,
32
+ },
33
+ }));
34
+ return;
35
+ }
36
+ storage.api
37
+ .getItem(`${userId}`)
38
+ .then((c2: ApiCartResponse) => {
39
+ if (!c2) return;
40
+
41
+ setCart({
42
+ items: JSON.parse(c2.cart),
43
+ authentication: {
44
+ loggedIn: true,
45
+ user_id: c2.user_id,
46
+ },
47
+ });
48
+ })
49
+ .catch(() => {});
50
+ }
@@ -1,28 +1,28 @@
1
- import { Cart, PathDetailsType } from "../types";
2
-
3
- export const defaultCartValue: Cart = {
4
- authentication: {
5
- loggedIn: false,
6
- },
7
- items: [],
8
- };
9
-
10
- export function fetchFromCartApi(
11
- method: "GET" | "PUT" | "DELETE",
12
- { baseUrl, userId }: PathDetailsType,
13
- body?: string
14
- ) {
15
- return fetch(`${baseUrl}/api/ecommerce/cart/${userId}`, {
16
- method,
17
- body,
18
- headers: {
19
- "Content-Type": "application/json",
20
- },
21
- });
22
- }
23
-
24
- export function pathDetailsIsFullyDefined(pathDetails: PathDetailsType) {
25
- if (pathDetails.userId === undefined) return false;
26
- if (pathDetails.baseUrl === undefined) return false;
27
- return true;
28
- }
1
+ import { Cart, PathDetailsType } from "../types";
2
+
3
+ export const defaultCartValue: Cart = {
4
+ authentication: {
5
+ loggedIn: false,
6
+ },
7
+ items: [],
8
+ };
9
+
10
+ export function fetchFromCartApi(
11
+ method: "GET" | "PUT" | "DELETE",
12
+ { baseUrl, userId }: PathDetailsType,
13
+ body?: string
14
+ ) {
15
+ return fetch(`${baseUrl}/api/ecommerce/cart/${userId}`, {
16
+ method,
17
+ body,
18
+ headers: {
19
+ "Content-Type": "application/json",
20
+ },
21
+ });
22
+ }
23
+
24
+ export function pathDetailsIsFullyDefined(pathDetails: PathDetailsType) {
25
+ if (pathDetails.userId === undefined) return false;
26
+ if (pathDetails.baseUrl === undefined) return false;
27
+ return true;
28
+ }
@@ -1,133 +1,133 @@
1
- import {
2
- fetchFromCartApi,
3
- defaultCartValue,
4
- pathDetailsIsFullyDefined,
5
- } from "./";
6
- import { persistentAtom } from "@nanostores/persistent";
7
- import { atom } from "nanostores";
8
- import { Cart, CartProduct, PathDetailsType } from "../types";
9
-
10
- export const cartStore = persistentAtom(
11
- "cart",
12
- JSON.stringify(defaultCartValue)
13
- );
14
-
15
- export const apiPathDetails = atom<PathDetailsType>({});
16
-
17
- function cartProductToCartDataItemIds(product: CartProduct) {
18
- return {
19
- ...product,
20
- image: undefined,
21
- name: undefined,
22
- };
23
- }
24
-
25
- apiPathDetails.listen((pathDetails) => {
26
- if (pathDetailsIsFullyDefined(pathDetails)) {
27
- // Runs on init if there is a user id and api key. Automatically logs in if userId is updated from undefined.
28
- fetchFromCartApi("GET", pathDetails).then(async (c) => {
29
- const cart = await c.json();
30
- cartStore.set(
31
- JSON.stringify({
32
- authentication: { loggedIn: true, user_id: cart.user_id },
33
- items: JSON.parse((cart as any).items),
34
- order: cart.order ? JSON.parse((cart as any).order) : undefined,
35
- })
36
- );
37
- });
38
- } else {
39
- const localCartData = JSON.parse(cartStore.get());
40
- if (localCartData.authentication.loggedIn)
41
- cartStore.set(JSON.stringify(defaultCartValue));
42
- }
43
- });
44
-
45
- export function addToCart(p: CartProduct) {
46
- const cart: Cart = JSON.parse(cartStore.get());
47
- const newCart: Cart = {
48
- ...cart,
49
- items: [...cart.items, p],
50
- order: undefined,
51
- };
52
-
53
- const pathDetails = apiPathDetails.get();
54
- if (pathDetailsIsFullyDefined(pathDetails)) {
55
- fetchFromCartApi(
56
- "PUT",
57
- pathDetails,
58
- JSON.stringify({
59
- user_id: pathDetails.userId,
60
- items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
61
- })
62
- ).then(async () => {
63
- cartStore.set(JSON.stringify(newCart));
64
- });
65
- } else {
66
- cartStore.set(JSON.stringify(newCart));
67
- }
68
- }
69
-
70
- export function removeFromCart(i: number) {
71
- const cart: Cart = JSON.parse(cartStore.get());
72
-
73
- const products: CartProduct[] = [...cart.items];
74
- products.splice(i, 1);
75
- const newCart: Cart = { ...cart, items: products, order: undefined };
76
-
77
- const pathDetails = apiPathDetails.get();
78
- if (pathDetailsIsFullyDefined(pathDetails)) {
79
- // If products.length is 0, delete cart. Otheriwise, update cart.
80
- const cartIsEmpty = products.length > 0;
81
-
82
- const body = {
83
- user_id: pathDetails.userId,
84
- items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
85
- };
86
-
87
- fetchFromCartApi(
88
- cartIsEmpty ? "PUT" : "DELETE",
89
- pathDetails,
90
- cartIsEmpty ? JSON.stringify(body) : undefined
91
- ).then(async () => {
92
- cartStore.set(JSON.stringify(newCart));
93
- });
94
- } else {
95
- cartStore.set(JSON.stringify(newCart));
96
- }
97
- }
98
-
99
- export function clearCart() {
100
- const cart: Cart = JSON.parse(cartStore.get());
101
- const newCart: Cart = { ...cart, items: [], order: undefined };
102
-
103
- const pathDetails = apiPathDetails.get();
104
- if (pathDetailsIsFullyDefined(pathDetails)) {
105
- fetchFromCartApi("DELETE", pathDetails).then(async () => {
106
- cartStore.set(JSON.stringify(newCart));
107
- });
108
- } else {
109
- cartStore.set(JSON.stringify(newCart));
110
- }
111
- }
112
-
113
- export function setOrder(order: { id: number; reference: string }) {
114
- const cart: Cart = JSON.parse(cartStore.get());
115
- const newCart: Cart = { ...cart, order };
116
-
117
- const pathDetails = apiPathDetails.get();
118
- if (pathDetailsIsFullyDefined(pathDetails)) {
119
- fetchFromCartApi(
120
- "PUT",
121
- pathDetails,
122
- JSON.stringify({
123
- user_id: pathDetails.userId,
124
- items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
125
- order: JSON.stringify(order),
126
- })
127
- ).then(async () => {
128
- cartStore.set(JSON.stringify(newCart));
129
- });
130
- } else {
131
- cartStore.set(JSON.stringify(newCart));
132
- }
133
- }
1
+ import {
2
+ fetchFromCartApi,
3
+ defaultCartValue,
4
+ pathDetailsIsFullyDefined,
5
+ } from "./";
6
+ import { persistentAtom } from "@nanostores/persistent";
7
+ import { atom } from "nanostores";
8
+ import { Cart, CartProduct, PathDetailsType } from "../types";
9
+
10
+ export const cartStore = persistentAtom(
11
+ "cart",
12
+ JSON.stringify(defaultCartValue)
13
+ );
14
+
15
+ export const apiPathDetails = atom<PathDetailsType>({});
16
+
17
+ function cartProductToCartDataItemIds(product: CartProduct) {
18
+ return {
19
+ ...product,
20
+ image: undefined,
21
+ name: undefined,
22
+ };
23
+ }
24
+
25
+ apiPathDetails.listen((pathDetails) => {
26
+ if (pathDetailsIsFullyDefined(pathDetails)) {
27
+ // Runs on init if there is a user id and api key. Automatically logs in if userId is updated from undefined.
28
+ fetchFromCartApi("GET", pathDetails).then(async (c) => {
29
+ const cart = await c.json();
30
+ cartStore.set(
31
+ JSON.stringify({
32
+ authentication: { loggedIn: true, user_id: cart.user_id },
33
+ items: JSON.parse((cart as any).items),
34
+ order: cart.order ? JSON.parse((cart as any).order) : undefined,
35
+ })
36
+ );
37
+ });
38
+ } else {
39
+ const localCartData = JSON.parse(cartStore.get());
40
+ if (localCartData.authentication.loggedIn)
41
+ cartStore.set(JSON.stringify(defaultCartValue));
42
+ }
43
+ });
44
+
45
+ export function addToCart(p: CartProduct) {
46
+ const cart: Cart = JSON.parse(cartStore.get());
47
+ const newCart: Cart = {
48
+ ...cart,
49
+ items: [...cart.items, p],
50
+ order: undefined,
51
+ };
52
+
53
+ const pathDetails = apiPathDetails.get();
54
+ if (pathDetailsIsFullyDefined(pathDetails)) {
55
+ fetchFromCartApi(
56
+ "PUT",
57
+ pathDetails,
58
+ JSON.stringify({
59
+ user_id: pathDetails.userId,
60
+ items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
61
+ })
62
+ ).then(async () => {
63
+ cartStore.set(JSON.stringify(newCart));
64
+ });
65
+ } else {
66
+ cartStore.set(JSON.stringify(newCart));
67
+ }
68
+ }
69
+
70
+ export function removeFromCart(i: number) {
71
+ const cart: Cart = JSON.parse(cartStore.get());
72
+
73
+ const products: CartProduct[] = [...cart.items];
74
+ products.splice(i, 1);
75
+ const newCart: Cart = { ...cart, items: products, order: undefined };
76
+
77
+ const pathDetails = apiPathDetails.get();
78
+ if (pathDetailsIsFullyDefined(pathDetails)) {
79
+ // If products.length is 0, delete cart. Otheriwise, update cart.
80
+ const cartIsEmpty = products.length > 0;
81
+
82
+ const body = {
83
+ user_id: pathDetails.userId,
84
+ items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
85
+ };
86
+
87
+ fetchFromCartApi(
88
+ cartIsEmpty ? "PUT" : "DELETE",
89
+ pathDetails,
90
+ cartIsEmpty ? JSON.stringify(body) : undefined
91
+ ).then(async () => {
92
+ cartStore.set(JSON.stringify(newCart));
93
+ });
94
+ } else {
95
+ cartStore.set(JSON.stringify(newCart));
96
+ }
97
+ }
98
+
99
+ export function clearCart() {
100
+ const cart: Cart = JSON.parse(cartStore.get());
101
+ const newCart: Cart = { ...cart, items: [], order: undefined };
102
+
103
+ const pathDetails = apiPathDetails.get();
104
+ if (pathDetailsIsFullyDefined(pathDetails)) {
105
+ fetchFromCartApi("DELETE", pathDetails).then(async () => {
106
+ cartStore.set(JSON.stringify(newCart));
107
+ });
108
+ } else {
109
+ cartStore.set(JSON.stringify(newCart));
110
+ }
111
+ }
112
+
113
+ export function setOrder(order: { id: number; reference: string }) {
114
+ const cart: Cart = JSON.parse(cartStore.get());
115
+ const newCart: Cart = { ...cart, order };
116
+
117
+ const pathDetails = apiPathDetails.get();
118
+ if (pathDetailsIsFullyDefined(pathDetails)) {
119
+ fetchFromCartApi(
120
+ "PUT",
121
+ pathDetails,
122
+ JSON.stringify({
123
+ user_id: pathDetails.userId,
124
+ items: newCart.items.map((p) => cartProductToCartDataItemIds(p)),
125
+ order: JSON.stringify(order),
126
+ })
127
+ ).then(async () => {
128
+ cartStore.set(JSON.stringify(newCart));
129
+ });
130
+ } else {
131
+ cartStore.set(JSON.stringify(newCart));
132
+ }
133
+ }
package/tsconfig.json CHANGED
@@ -1,24 +1,24 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "useDefineForClassFields": true,
5
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
- "module": "ESNext",
7
- "skipLibCheck": true,
8
-
9
- /* Bundler mode */
10
- "moduleResolution": "bundler",
11
- "allowImportingTsExtensions": true,
12
- "resolveJsonModule": true,
13
- "isolatedModules": true,
14
- "noEmit": true,
15
- "jsx": "react-jsx",
16
-
17
- /* Linting */
18
- "strict": false,
19
- "noFallthroughCasesInSwitch": true,
20
- "noImplicitAny": false
21
- },
22
- "include": ["src"],
23
- "references": [{ "path": "./tsconfig.node.json" }]
24
- }
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "useDefineForClassFields": true,
5
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
+ "module": "ESNext",
7
+ "skipLibCheck": true,
8
+
9
+ /* Bundler mode */
10
+ "moduleResolution": "bundler",
11
+ "allowImportingTsExtensions": true,
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "noEmit": true,
15
+ "jsx": "react-jsx",
16
+
17
+ /* Linting */
18
+ "strict": false,
19
+ "noFallthroughCasesInSwitch": true,
20
+ "noImplicitAny": false
21
+ },
22
+ "include": ["src"],
23
+ "references": [{ "path": "./tsconfig.node.json" }]
24
+ }
@@ -1,11 +1,11 @@
1
- {
2
- "compilerOptions": {
3
- "composite": true,
4
- "skipLibCheck": true,
5
- "module": "ESNext",
6
- "moduleResolution": "bundler",
7
- "allowSyntheticDefaultImports": true,
8
- "strict": true
9
- },
10
- "include": ["vite.config.ts"]
11
- }
1
+ {
2
+ "compilerOptions": {
3
+ "composite": true,
4
+ "skipLibCheck": true,
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "allowSyntheticDefaultImports": true,
8
+ "strict": true
9
+ },
10
+ "include": ["vite.config.ts"]
11
+ }