Skip to content

Commit

Permalink
io client for vtexio
Browse files Browse the repository at this point in the history
  • Loading branch information
tlgimenes committed Sep 3, 2023
1 parent 45069ad commit 34a1a6d
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 62 deletions.
22 changes: 19 additions & 3 deletions utils/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type GraphQLAPI<D = unknown> = Record<string, {
body: {
query: string;
variables?: Record<string, unknown>;
operationName?: string;
};
}>;

Expand All @@ -26,14 +27,29 @@ export const createGraphqlClient = (
) => {
const url = new URL(endpoint);
const key = `POST ${url.pathname}`;
const http = createHttpClient<GraphQLAPI>({ ...rest, base: url.origin });

const defaultHeaders = new Headers(rest.headers);
defaultHeaders.set("content-type", "application/json");
defaultHeaders.set("accept", "application/json");

const http = createHttpClient<GraphQLAPI>({
...rest,
base: url.origin,
headers: defaultHeaders,
});

return {
query: async <D, V>(
{ query = "", variables }: { query: string; variables?: V },
{ query = "", variables, operationName }: {
query: string;
variables?: V;
operationName?: string;
},
init?: RequestInit,
): Promise<D> => {
const { data, errors } = await http[key as any]({}, {
body: { query, variables: variables as any },
...init,
body: { query, variables: variables as any, operationName },
}).then((res) => res.json());

if (Array.isArray(errors) && errors.length > 0) {
Expand Down
27 changes: 10 additions & 17 deletions vtex/actions/wishlist/addItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,24 @@ const action = async (
req: Request,
ctx: AppContext,
): Promise<WishlistItem[]> => {
const { vcs } = ctx;
const { io } = ctx;
const { cookie, payload } = parseCookie(req.headers, ctx.account);
const user = payload?.sub;

if (!user) {
return [];
}

await vcs["POST /api/io/_v/private/graphql/v1"]({}, {
body: {
operationName: "AddToWishlist",
variables: {
name: "Wishlist",
shopperId: user,
listItem: props,
},
query:
`mutation AddToWishlist($listItem: ListItemInputType!, $shopperId: String!, $name: String!, $public: Boolean) { addToList(listItem: $listItem, shopperId: $shopperId, name: $name, public: $public) @context(provider: "[email protected]") }`,
await io.query({
operationName: "AddToWishlist",
variables: {
name: "Wishlist",
shopperId: user,
listItem: props,
},
headers: {
"content-type": "application/json",
accept: "application/json",
cookie,
},
});
query:
`mutation AddToWishlist($listItem: ListItemInputType!, $shopperId: String!, $name: String!, $public: Boolean) { addToList(listItem: $listItem, shopperId: $shopperId, name: $name, public: $public) @context(provider: "[email protected]") }`,
}, { headers: { cookie } });

return wishlistLoader({ count: Infinity }, req, ctx);
};
Expand Down
27 changes: 10 additions & 17 deletions vtex/actions/wishlist/removeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const action = async (
req: Request,
ctx: AppContext,
): Promise<WishlistItem[]> => {
const { vcs } = ctx;
const { io } = ctx;
const { cookie, payload } = parseCookie(req.headers, ctx.account);
const user = payload?.sub;
const { id } = props;
Expand All @@ -19,23 +19,16 @@ const action = async (
return [];
}

await vcs["POST /api/io/_v/private/graphql/v1"]({}, {
body: {
operationName: "RemoveFromList",
variables: {
name: "Wishlist",
shopperId: user,
id,
},
query:
`mutation RemoveFromList($id: ID!, $shopperId: String!, $name: String) { removeFromList(id: $id, shopperId: $shopperId, name: $name) @context(provider: "[email protected]") }`,
await io.query({
operationName: "RemoveFromList",
variables: {
name: "Wishlist",
shopperId: user,
id,
},
headers: {
"content-type": "application/json",
accept: "application/json",
cookie,
},
});
query:
`mutation RemoveFromList($id: ID!, $shopperId: String!, $name: String) { removeFromList(id: $id, shopperId: $shopperId, name: $name) @context(provider: "[email protected]") }`,
}, { headers: { cookie } });

return wishlistLoader({ count: Infinity }, req, ctx);
};
Expand Down
30 changes: 14 additions & 16 deletions vtex/loaders/wishlist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const loader = async (
req: Request,
ctx: AppContext,
): Promise<WishlistItem[]> => {
const { vcs } = ctx;
const { io } = ctx;
const url = new URL(req.url);
const page = Number(url.searchParams.get("page")) || 0;
const count = props.count || Infinity;
Expand All @@ -28,28 +28,26 @@ const loader = async (
}

try {
const { data } = await vcs["POST /api/io/_v/private/graphql/v1"]({}, {
body: {
operationName: "GetWithlist",
variables: {
name: "Wishlist",
shopperId: user,
},
query:
`query GetWithlist($shopperId: String!, $name: String!, $from: Int, $to: Int) { viewList(shopperId: $shopperId, name: $name, from: $from, to: $to) @context(provider: "[email protected]") { name data { id productId sku title } } }`,
const { viewList } = await io.query<
{ viewList: { name?: string; data: WishlistItem[] } },
{ name: string; shopperId: string }
>({
operationName: "GetWithlist",
variables: {
name: "Wishlist",
shopperId: user,
},
query:
`query GetWithlist($shopperId: String!, $name: String!, $from: Int, $to: Int) { viewList(shopperId: $shopperId, name: $name, from: $from, to: $to) @context(provider: "[email protected]") { name data { id productId sku title } } }`,
}, {
headers: {
"content-type": "application/json",
accept: "application/json",
cookie,
},
}).then((res) =>
res.json() as {
data?: { viewList: { name?: string; data: WishlistItem[] } };
}
);
});

return data?.viewList.data?.slice(count * page, count * (page + 1)) ?? [];
return viewList.data?.slice(count * page, count * (page + 1)) ?? [];
} catch {
return [];
}
Expand Down
9 changes: 8 additions & 1 deletion vtex/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { fetchSafe } from "./utils/fetchVTEX.ts";
import { createHttpClient } from "../utils/http.ts";
import manifest, { Manifest } from "./manifest.gen.ts";
import { SP, VTEXCommerceStable } from "./utils/client.ts";
import { createGraphqlClient } from "../utils/graphql.ts";

export type AppContext = FnContext<State, Manifest>;

Expand All @@ -28,6 +29,7 @@ export interface Props {
interface State extends Props {
vcs: ReturnType<typeof createHttpClient<VTEXCommerceStable>>;
sp: ReturnType<typeof createHttpClient<SP>>;
io: ReturnType<typeof createGraphqlClient>;
}

/**
Expand All @@ -42,9 +44,14 @@ export default function App(state: Props): App<Manifest, State> {
base: `https://${state.account}.vtexcommercestable.com.br`,
fetcher: fetchSafe,
});
const io = createGraphqlClient({
endpoint:
`https://${state.account}.vtexcommercestable.com.br/api/io/_v/private/graphql/v1`,
fetcher: fetchSafe,
});

return {
state: { ...state, vcs, sp },
state: { ...state, vcs, sp, io },
manifest,
};
}
8 changes: 0 additions & 8 deletions vtex/utils/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ import {
} from "./types.ts";

export interface VTEXCommerceStable {
"POST /api/io/_v/private/graphql/v1": {
response: { data: unknown; errors: unknown[] };
body: {
operationName: string;
variables: Record<string, unknown>;
query: string;
};
};
"POST /no-cache/Newsletter.aspx": { body: FormData };
"POST /no-cache/AviseMe.aspx": { body: FormData };
"GET /api/catalog_system/pub/portal/pagetype/:term": { response: PageType };
Expand Down

0 comments on commit 34a1a6d

Please sign in to comment.