@springmicro/cart 0.7.0 → 0.7.2

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/types.d.ts CHANGED
@@ -1,56 +1,58 @@
1
- export interface Cart {
2
- authentication: {
3
- loggedIn: boolean;
4
- user_id?: number | string;
5
- };
6
- items: CartProduct[];
7
- order?: {
8
- id: number;
9
- reference: string;
10
- };
11
- }
12
- export type CartProduct = {
13
- product_id: number | string;
14
- price_id: number | string;
15
- quantity?: number;
16
- // Used in local cart, delete when sent to api
17
- name: string;
18
- image?: string;
19
- };
20
-
21
- type CartContextType = {
22
- cart: Cart;
23
- addToCart: (p: CartProduct) => void;
24
- removeFromCart: (i: number) => void;
25
- clearCart: () => void;
26
- };
27
-
28
- type ApiCartResponse = {
29
- cart: string;
30
- id: any;
31
- user_id: number | string;
32
- };
33
-
34
- export type PathDetailsType = {
35
- baseUrl?: string;
36
- userId?: string | number;
37
- };
38
-
39
- export type Product = {
40
- id: string | number;
41
- name: string;
42
- /** v Parses to @type {ProductPricing} v */
43
- pricing: string;
44
- description?: string;
45
- } & unknown;
46
-
47
- export type ProductPricing = {
48
- id: number | string;
49
- unit_amount: number; // in cents
50
- recurring?: {
51
- interval: "month" | "week" | "day";
52
- interval_count: number;
53
- };
54
- tier_label?: string;
55
- tier_description?: string;
56
- };
1
+ export interface Cart {
2
+ authentication: {
3
+ loggedIn: boolean;
4
+ user_id?: number | string;
5
+ };
6
+ items: CartProduct[];
7
+ order?: {
8
+ id: number;
9
+ reference: string;
10
+ };
11
+ }
12
+ export type CartProduct = {
13
+ product_id: number | string;
14
+ price_id: number | string;
15
+ quantity?: number;
16
+ // Used in local cart, delete when sent to api
17
+ name: string;
18
+ action_data?: object;
19
+ hidden_id?: string;
20
+ image?: string;
21
+ };
22
+
23
+ type CartContextType = {
24
+ cart: Cart;
25
+ addToCart: (p: CartProduct) => void;
26
+ removeFromCart: (i: number) => void;
27
+ clearCart: () => void;
28
+ };
29
+
30
+ type ApiCartResponse = {
31
+ cart: string;
32
+ id: any;
33
+ user_id: number | string;
34
+ };
35
+
36
+ export type PathDetailsType = {
37
+ baseUrl?: string;
38
+ userId?: string | number;
39
+ };
40
+
41
+ export type Product = {
42
+ id: string | number;
43
+ name: string;
44
+ /** v Parses to @type {ProductPricing} v */
45
+ pricing: string;
46
+ description?: string;
47
+ } & unknown;
48
+
49
+ export type ProductPricing = {
50
+ id: number | string;
51
+ unit_amount: number; // in cents
52
+ recurring?: {
53
+ interval: "month" | "week" | "day";
54
+ interval_count: number;
55
+ };
56
+ tier_label?: string;
57
+ tier_description?: string;
58
+ };
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
+ }
File without changes
@@ -37,20 +37,31 @@ function apiCartToLocalCart(cart) {
37
37
  });
38
38
  }
39
39
 
40
+ function jsonOrObj(items) {
41
+ try {
42
+ return JSON.parse(items);
43
+ } catch {
44
+ return items;
45
+ }
46
+ }
47
+
40
48
  apiPathDetails.listen((pathDetails, oldPathDetails) => {
41
49
  const localCartData = JSON.parse(cartStore.get());
42
50
  if (pathDetailsIsFullyDefined(pathDetails)) {
43
51
  // Runs on init if there is a user id and api key. Automatically logs in if userId is updated from undefined.
44
- fetchFromCartApi("GET", pathDetails).then(async ({ status, json }) => {
52
+ fetchFromCartApi("GET", pathDetails).then(async (res) => {
53
+ const { status } = res;
45
54
  if (status === 200) {
46
- const cart = await json();
47
- cartStore.set(
48
- JSON.stringify({
49
- authentication: { loggedIn: true, user_id: cart.user_id },
50
- items: JSON.parse((cart as any).items),
51
- order: cart.order ? JSON.parse((cart as any).order) : undefined,
52
- })
53
- );
55
+ const cart = await res.json();
56
+
57
+ const cartStr = JSON.stringify({
58
+ authentication: { loggedIn: true, user_id: cart.user_id },
59
+ items: jsonOrObj(cart.items),
60
+ order: cart.order ? jsonOrObj(cart.order) : undefined,
61
+ });
62
+
63
+ cartStore.set(cartStr);
64
+ console.log(cartStr);
54
65
  } else if (status === 404 && localCartData.items.length > 0) {
55
66
  fetchFromCartApi(
56
67
  "PUT",
@@ -59,11 +70,19 @@ apiPathDetails.listen((pathDetails, oldPathDetails) => {
59
70
  ).then(async ({ ok, json }) => {
60
71
  if (!ok) return;
61
72
  const cart = await json();
73
+ console.log(
74
+ "Update local cart",
75
+ JSON.stringify({
76
+ authentication: { loggedIn: true, user_id: cart.user_id },
77
+ items: jsonOrObj(cart.items),
78
+ order: cart.order ? jsonOrObj(cart.order) : undefined,
79
+ })
80
+ );
62
81
  cartStore.set(
63
82
  JSON.stringify({
64
83
  authentication: { loggedIn: true, user_id: cart.user_id },
65
- items: JSON.parse((cart as any).items),
66
- order: cart.order ? JSON.parse((cart as any).order) : undefined,
84
+ items: jsonOrObj(cart.items),
85
+ order: cart.order ? jsonOrObj(cart.order) : undefined,
67
86
  })
68
87
  );
69
88
  });
@@ -96,6 +115,7 @@ export function logout(apiBaseUrl: string | undefined) {
96
115
  }
97
116
 
98
117
  export function addToCart(p: CartProduct) {
118
+ console.log("ADD TO CART", p);
99
119
  const cart: Cart = JSON.parse(cartStore.get());
100
120
  const newCart: Cart = {
101
121
  ...cart,
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
+ }
package/vite.config.ts CHANGED
@@ -1,25 +1,25 @@
1
- import react from "@vitejs/plugin-react";
2
- import { resolve } from "path";
3
- import { defineConfig } from "vite";
4
- import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
5
-
6
- export default defineConfig({
7
- plugins: [react(), cssInjectedByJsPlugin()],
8
- build: {
9
- lib: {
10
- entry: resolve(__dirname, "src/index.ts"),
11
- name: "@springmicro/cart",
12
- fileName: "index",
13
- },
14
- rollupOptions: {
15
- external: ["react", "react-dom", "nanoid"],
16
- output: {
17
- globals: {
18
- react: "React",
19
- "react-dom": "ReactDOM",
20
- nanoid: "Nanoid",
21
- },
22
- },
23
- },
24
- },
25
- });
1
+ import react from "@vitejs/plugin-react";
2
+ import { resolve } from "path";
3
+ import { defineConfig } from "vite";
4
+ import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
5
+
6
+ export default defineConfig({
7
+ plugins: [react(), cssInjectedByJsPlugin()],
8
+ build: {
9
+ lib: {
10
+ entry: resolve(__dirname, "src/index.ts"),
11
+ name: "@springmicro/cart",
12
+ fileName: "index",
13
+ },
14
+ rollupOptions: {
15
+ external: ["react", "react-dom", "nanoid"],
16
+ output: {
17
+ globals: {
18
+ react: "React",
19
+ "react-dom": "ReactDOM",
20
+ nanoid: "Nanoid",
21
+ },
22
+ },
23
+ },
24
+ },
25
+ });