Build a full-stack single-click search keyword app for BigCommerce 

Expected time: 25 minutes

This tutorial will show you how to build a full-stack, single-click app for BigCommerce.

Adding appropriate search keywords to products is important so shoppers can find exactly what they are looking for when shopping on BigCommerce storefronts. This app will allow merchants to enter keywords, check to see if those keywords exist in product descriptions, and add them as search_keywords on products.

A screenshot of the completed application, embedded in a BigCommerce control panel. The top of the page is a form with a single input for entering keywords, the bottom of the page is a table with existing keywords.

By the end of this tutorial, you will have:

  • Set up a BigCommerce connection
  • Subscribed to BigCommerce webhooks
  • Stored BigCommerce data in a Gadget database
  • Built a complete serverless Node.js backend
  • Used the BigDesign library to build a React frontend
  • (Optional) Sync historical product data from BigCommerce
Prefer a video? 
Prefer a video?

If you prefer video tutorials, you can build along with our video on Youtube.

Prerequisites 

Before starting, you will need:

Step 1: Create a new Gadget app and connect to BigCommerce 

We will start by creating a new Gadget app and connecting to BigCommerce.

  1. Create a new Gadget app at gadget.new, select the BigCommerce app type, and give your app a name.
  2. Click the Connect to BigCommerce button on your app's home page.
  3. Create a new BigCommerce app in the BigCommerce Developer Portal.
  4. Copy the Auth callback URL and Load callback URL from Gadget to your BigCommerce app.
  5. Select the Products Modify OAuth scope and click Update & Close in the BigCommerce app.
  6. In the BigCommerce Developer Portal, click View Client ID for your new app and copy the Client ID and Client Secret to Gadget, then click Continue.
  7. In your BigCommerce sandbox store, navigate to Apps → My Draft Apps, hover over your newly added app, click Learn more.
  8. Click Install.

We now have a full-stack, single-click BigCommerce app in our store control panel! OAuth and frontend sessions are handled, and we can subscribe to BigCommerce webhooks.

Step 2: Create data models for products and search keywords 

We need to store both product data and search keywords entered by merchants in our Gadget database. We can create data models in Gadget to store this data.

  1. Right-click on the api/models/bigcommerce directory in the Gadget file tree and select Add model.
  2. Name the model product and add the following fields and validations:
Field nameField typeValidations
bigcommerceIdnumberUniqueness, Required
namestringRequired
descriptionstring
searchKeywordsstring
storebelongs toRequired
typeenum (with options: digital & physical)Required
weightnumberRequired
pricenumberRequired
  1. For the store field, select the bigcommerce/store model as the parent model, so that bigcommerce/store has many bigcommerce/product.
A screenshot of the store relationship field on the bigcommerce/product model. The inverse of the relationship is a has many, so that bigcommerce/store has many bigcommerce/product records.
  1. For the type field, add the following options: physical and digital.
A screenshot of the enum options for the bigcommerce/product model's type field.
bigcommerceId uniqueness validation

For multi-tenant apps, you may have multiple stores whose resources have the same bigcommerceId. To avoid conflicts, you can scope the Uniqueness validation on bigcommerceId by the store relationship. This ensures that bigcommerceId is unique per store.

  1. Click the + button next to api/models to create another new model. (Note: this will create a new model outside of the bigcommerce namespace.)
  2. Name the model searchKeyword and give it the following field and validations:
Field nameField typeValidations
valuestringUniqueness, Required

We have successfully set up our data models! This also generated a CRUD (Create, Read, Update, Delete) API for each model that we can use to interact with our data.

Why store product data?

Product data needs to be stored to avoid webhook looping on store/product/updated webhooks. If no data is stored, change detection cannot be used to see if a product must be updated.

Step 3: Subscribe to store/product webhooks 

Now we can subscribe to webhooks and use them to run some code that will check for stored search keywords in product descriptions. If a keyword is found, we will write that keyword back to the product in BigCommerce.

  1. Click the + button next to api/actions and enter bigcommerce/handleProductWebhooks.js. This creates a bigcommerce namespace folder and our new action.
  2. Click the + button in the action's Triggers card and select BigCommerce.
  3. Select the store/product/created, store/product/updated, and store/product/deleted webhook scopes.
  4. (Optional) Remove the Generated API endpoint trigger from the action.

Now this action will run anytime a product is created, updated, or deleted in BigCommerce!

When a product webhook is fired, we want to call the bigcommerce/product model's actions to create, update, or delete records in the Gadget database.

Notice that the upsert meta API is used to handle store/product/updated webhooks. This is because the product may not yet exist in our database if we haven't synced historical data.

  1. Paste the following code in api/actions/bigcommerce/handleProductWebhooks.js:
api/actions/bigcommerce/handleProductWebhooks.js
JavaScript
1import { ActionOptions } from "gadget-server";
2
3export const run: ActionRun = async ({ params, api, connections, trigger }) => {
4 if (trigger.type !== "bigcommerce_webhook") {
5 throw new Error("This action can only be triggered by BigCommerce webhooks");
6 }
7
8 // handle deletes early, don't need to query BigCommerce, just need to remove data from Gadget
9 if (trigger.scope === "store/product/deleted") {
10 // see if product exists in database
11 const productRecordToDelete = await api.bigcommerce.product.maybeFindFirst({
12 filter: { bigcommerceId: { equals: params.id } },
13 select: { id: true },
14 });
15 if (productRecordToDelete) {
16 // if it exists, delete it
17 await api.bigcommerce.product.delete(productRecordToDelete.id);
18 }
19 return;
20 }
21
22 // get the BigCommerce API client for the current store
23 const bigcommerce = connections.bigcommerce.current!;
24
25 // fetch the product data
26 const product = await bigcommerce.v3.get("/catalog/products/{product_id}", {
27 path: {
28 product_id: params.id,
29 },
30 });
31
32 if (product) {
33 // split out fields we are storing in database
34 const productToSave = {
35 bigcommerceId: product.id,
36 name: product.name,
37 description: product.description,
38 searchKeywords: product.search_keywords,
39 store: {
40 // get the id of the store record in Gadget to create the relationship
41 _link: connections.bigcommerce.currentStoreId,
42 },
43 type: product.type,
44 price: product.price,
45 weight: product.weight,
46 };
47
48 // a switch statement to handle different product webhook topics
49 // use the trigger parameter to access the webhook scope
50 switch (trigger.scope) {
51 case "store/product/created":
52 // add product to database
53 await api.bigcommerce.product.create(productToSave);
54 break;
55 case "store/product/updated":
56 // upsert the product into the database, using the bigcommerceId as the key identifier
57 await api.bigcommerce.product.upsert({
58 ...productToSave,
59 on: ["bigcommerceId", "store"],
60 });
61 break;
62 }
63 } else {
64 throw new Error(`Product ${params.id} not found in BigCommerce store!`);
65 }
66};
67
68export const options: ActionOptions = {
69 triggers: {
70 api: false,
71 bigcommerce: {
72 webhooks: [
73 "store/product/created",
74 "store/product/updated",
75 "store/product/deleted",
76 ],
77 },
78 },
79};
1import { ActionOptions } from "gadget-server";
2
3export const run: ActionRun = async ({ params, api, connections, trigger }) => {
4 if (trigger.type !== "bigcommerce_webhook") {
5 throw new Error("This action can only be triggered by BigCommerce webhooks");
6 }
7
8 // handle deletes early, don't need to query BigCommerce, just need to remove data from Gadget
9 if (trigger.scope === "store/product/deleted") {
10 // see if product exists in database
11 const productRecordToDelete = await api.bigcommerce.product.maybeFindFirst({
12 filter: { bigcommerceId: { equals: params.id } },
13 select: { id: true },
14 });
15 if (productRecordToDelete) {
16 // if it exists, delete it
17 await api.bigcommerce.product.delete(productRecordToDelete.id);
18 }
19 return;
20 }
21
22 // get the BigCommerce API client for the current store
23 const bigcommerce = connections.bigcommerce.current!;
24
25 // fetch the product data
26 const product = await bigcommerce.v3.get("/catalog/products/{product_id}", {
27 path: {
28 product_id: params.id,
29 },
30 });
31
32 if (product) {
33 // split out fields we are storing in database
34 const productToSave = {
35 bigcommerceId: product.id,
36 name: product.name,
37 description: product.description,
38 searchKeywords: product.search_keywords,
39 store: {
40 // get the id of the store record in Gadget to create the relationship
41 _link: connections.bigcommerce.currentStoreId,
42 },
43 type: product.type,
44 price: product.price,
45 weight: product.weight,
46 };
47
48 // a switch statement to handle different product webhook topics
49 // use the trigger parameter to access the webhook scope
50 switch (trigger.scope) {
51 case "store/product/created":
52 // add product to database
53 await api.bigcommerce.product.create(productToSave);
54 break;
55 case "store/product/updated":
56 // upsert the product into the database, using the bigcommerceId as the key identifier
57 await api.bigcommerce.product.upsert({
58 ...productToSave,
59 on: ["bigcommerceId", "store"],
60 });
61 break;
62 }
63 } else {
64 throw new Error(`Product ${params.id} not found in BigCommerce store!`);
65 }
66};
67
68export const options: ActionOptions = {
69 triggers: {
70 api: false,
71 bigcommerce: {
72 webhooks: [
73 "store/product/created",
74 "store/product/updated",
75 "store/product/deleted",
76 ],
77 },
78 },
79};

This will handle the product webhook topics and call the required bigcommerce/product action.

Action parameters

Gadget actions have a high-context parameter that provides you with everything you need to interact with the rest of your app.

In this example, we use:

  • params to get the product ID from the webhook payload
  • api to call our app's API and interact with our database
  • connections to get the BigCommerce API client
  • trigger to read the webhook topic
  • logger to write to Gadget's built-in Logs tool

Step 4: Write search keywords back to BigCommerce 

When a product is created or updated in BigCommerce, we want to check the product description for search keywords. If a keyword is found, we will write it back to the product in BigCommerce.

We want to run this code when we create a new product or update an existing product. We can create a utility function to handle this logic and call it from our create and update actions.

  1. Create a utils.js file in the api/models/bigcommerce/product directory.
  2. Add the following code to utils.js:
api/models/bigcommerce/product/utils.js
JavaScript
1import { api, logger, connections } from "gadget-server";
2
3export const getKeywords = async (record: {
4 description: string;
5 searchKeywords: string | null;
6 storeId: string;
7 bigcommerceId: number;
8 type: "physical" | "digital";
9 price: number;
10 weight: number;
11 name: string;
12}) => {
13 // get array of unique words in product description
14 const descriptionWords = [...new Set(record.description.match(/\w+(?:'\w+)*/g))];
15 // get array of entered search keywords
16 const savedKeywords = (await api.searchKeyword.findMany()).map(
17 (searchKeyword) => searchKeyword.value
18 );
19 // get the final list of keywords to be used for the product
20 let searchKeywords = [
21 ...new Set(descriptionWords.filter((tag) => savedKeywords.includes(tag))),
22 ];
23
24 // concatenate with existing searchKeywords, using a Set to remove duplicates
25 if (record.searchKeywords) {
26 searchKeywords = Array.from(
27 new Set(record.searchKeywords.split(",").concat(searchKeywords))
28 );
29 }
30
31 logger.info(
32 { descriptionWords, savedKeywords, searchKeywords },
33 "keyword and description info"
34 );
35
36 // get the storeHash for the current product
37 const store = await api.bigcommerce.store.findById(record.storeId, {
38 select: { storeHash: true },
39 });
40 // use the storeHash to get a BigCommerce API client for the current store
41 const bigcommerce = await connections.bigcommerce.forStoreHash(store.storeHash);
42 // update the search_keywords!
43 await bigcommerce.v3.put("/catalog/products/{product_id}", {
44 path: {
45 product_id: record.bigcommerceId,
46 },
47 body: {
48 search_keywords: searchKeywords.toString(),
49 type: record.type,
50 price: record.price,
51 weight: record.weight,
52 name: record.name,
53 },
54 });
55};
1import { api, logger, connections } from "gadget-server";
2
3export const getKeywords = async (record: {
4 description: string;
5 searchKeywords: string | null;
6 storeId: string;
7 bigcommerceId: number;
8 type: "physical" | "digital";
9 price: number;
10 weight: number;
11 name: string;
12}) => {
13 // get array of unique words in product description
14 const descriptionWords = [...new Set(record.description.match(/\w+(?:'\w+)*/g))];
15 // get array of entered search keywords
16 const savedKeywords = (await api.searchKeyword.findMany()).map(
17 (searchKeyword) => searchKeyword.value
18 );
19 // get the final list of keywords to be used for the product
20 let searchKeywords = [
21 ...new Set(descriptionWords.filter((tag) => savedKeywords.includes(tag))),
22 ];
23
24 // concatenate with existing searchKeywords, using a Set to remove duplicates
25 if (record.searchKeywords) {
26 searchKeywords = Array.from(
27 new Set(record.searchKeywords.split(",").concat(searchKeywords))
28 );
29 }
30
31 logger.info(
32 { descriptionWords, savedKeywords, searchKeywords },
33 "keyword and description info"
34 );
35
36 // get the storeHash for the current product
37 const store = await api.bigcommerce.store.findById(record.storeId, {
38 select: { storeHash: true },
39 });
40 // use the storeHash to get a BigCommerce API client for the current store
41 const bigcommerce = await connections.bigcommerce.forStoreHash(store.storeHash);
42 // update the search_keywords!
43 await bigcommerce.v3.put("/catalog/products/{product_id}", {
44 path: {
45 product_id: record.bigcommerceId,
46 },
47 body: {
48 search_keywords: searchKeywords.toString(),
49 type: record.type,
50 price: record.price,
51 weight: record.weight,
52 name: record.name,
53 },
54 });
55};

Now we can use this utility function in our create and update actions.

  1. Update api/models/bigcommerce/product/actions/create.js:
api/models/bigcommerce/product/actions/create.js
JavaScript
1import { applyParams, save, ActionOptions } from "gadget-server";
2import { getKeywords } from "../utils";
3
4export const run: ActionRun = async ({ params, record }) => {
5 applyParams(params, record);
6 await save(record);
7};
8
9export const onSuccess: ActionOnSuccess = async ({ record }) => {
10 if (record.storeId && record.description && record.description !== "") {
11 await getKeywords({
12 ...record,
13 storeId: record.storeId,
14 description: record.description,
15 });
16 }
17};
18
19export const options: ActionOptions = {
20 actionType: "create",
21};
1import { applyParams, save, ActionOptions } from "gadget-server";
2import { getKeywords } from "../utils";
3
4export const run: ActionRun = async ({ params, record }) => {
5 applyParams(params, record);
6 await save(record);
7};
8
9export const onSuccess: ActionOnSuccess = async ({ record }) => {
10 if (record.storeId && record.description && record.description !== "") {
11 await getKeywords({
12 ...record,
13 storeId: record.storeId,
14 description: record.description,
15 });
16 }
17};
18
19export const options: ActionOptions = {
20 actionType: "create",
21};
  1. Update api/models/bigcommerce/product/actions/update.js:
api/models/bigcommerce/product/actions/update.js
JavaScript
1import { ActionOptions, applyParams, save } from "gadget-server";
2import { getKeywords } from "../utils";
3
4export const run: ActionRun = async ({ params, record }) => {
5 applyParams(params, record);
6 await save(record);
7};
8
9export const onSuccess: ActionOnSuccess = async ({ record }) => {
10 if (
11 record.storeId &&
12 record.description &&
13 record.description !== "" &&
14 record.changed("description")
15 ) {
16 await getKeywords({
17 ...record,
18 storeId: record.storeId,
19 description: record.description,
20 });
21 }
22};
23
24export const options: ActionOptions = {
25 actionType: "update",
26};
1import { ActionOptions, applyParams, save } from "gadget-server";
2import { getKeywords } from "../utils";
3
4export const run: ActionRun = async ({ params, record }) => {
5 applyParams(params, record);
6 await save(record);
7};
8
9export const onSuccess: ActionOnSuccess = async ({ record }) => {
10 if (
11 record.storeId &&
12 record.description &&
13 record.description !== "" &&
14 record.changed("description")
15 ) {
16 await getKeywords({
17 ...record,
18 storeId: record.storeId,
19 description: record.description,
20 });
21 }
22};
23
24export const options: ActionOptions = {
25 actionType: "update",
26};

We have subscribed to webhooks and are writing data back to BigCommerce! Now we can build a frontend to allow merchants to enter search keywords.

Additional action info

We make use of the same high-context parameters in the create and update actions as we did in the webhook-handling global action. This allows us to interact with the database, BigCommerce API, and logger.

One key difference in model actions is that we also have a record parameter, which is the record being created or updated. In this case, it is our current bigcommerce/product record.

Read more about the record API and change detection used to prevent webhook looping.

Step 5: Grant merchants API access to search keywords 

All Gadget apps have authorization built in. A role-based access control system allows us to restrict API and data access to merchants and unauthenticated shoppers. Merchants won't have access to data stored in your custom models by default. We need to grant them access to our actions to be able to call them from our frontend.

  1. Navigate to the accessControl/permissions page.
  2. Grant the bigcommerce-app-users role access to the searchKeyword/ model's read, create, and delete actions.

The bigcommerce-app-users role is automatically assigned to merchants who install your app in BigCommerce. You can read more about the role in the docs.

Step 6: Build a React frontend with the BigDesign library 

We've finished building our database and backend, now we just need a frontend that allows merchants to enter search keywords.

The BigDesign library is pre-installed in Gadget and can be used to build a React frontend for single-click apps.

  1. Replace the code in web/routes/index.jsx with the following:
web/routes/index.jsx
React
1import { Box, Panel, Text, StatefulTable, Form, FormGroup, Input, Button, ProgressCircle, Message } from "@bigcommerce/big-design";
2import { DeleteIcon } from "@bigcommerce/big-design-icons";
3import { useFindMany, useActionForm, useBulkAction } from "@gadgetinc/react";
4import { useState } from "react";
5import { api } from "../api";
6
7export default function () {
8 const [selectedKeywordIds, setSelectedKeywordIds] = useState<string[]>([]);
9
10 // a useFindMany hook to fetch search keyword data
11 const [{ data, fetching, error }] = useFindMany(api.searchKeyword);
12
13 // the useAction hook is used for deleting existing keywords
14 const [{ error: deleteKeywordsError }, deleteKeywords] = useBulkAction(api.searchKeyword.bulkDelete);
15
16 // useActionForm used to manage form state and submission for creating new keywords
17 const { submit, register, reset, error: createError, formState } = useActionForm(api.searchKeyword.create);
18
19 return (
20 <>
21 <Panel>
22 {createError && <ErrorMessage title="Error adding keyword" error={createError} />}
23 <Form
24 onSubmit={async (event) => {
25 event.preventDefault();
26 await submit();
27 reset();
28 }}
29 >
30 <FormGroup>
31 <Input
32 description="Enter a new product search keyword"
33 label="Add search keywords"
34 required
35 {...register("value")}
36 autoComplete="off"
37 />
38 </FormGroup>
39 <Box marginTop="xxLarge">
40 <Button type="submit" disabled={formState.isSubmitting}>
41 Add keyword
42 </Button>
43 </Box>
44 </Form>
45 </Panel>
46 <Panel description="Current search keywords">
47 {fetching && <ProgressCircle size="large" />}
48 {error && <ErrorMessage title="Error reading keywords" error={error} />}
49 {deleteKeywordsError && <ErrorMessage title="Error removing keyword" error={deleteKeywordsError} />}
50 {data && (
51 <StatefulTable
52 stickyHeader
53 pagination
54 itemName="search keywords"
55 selectable
56 onSelectionChange={(value) => setSelectedKeywordIds(value.map((v) => v.id))}
57 columns={[
58 {
59 header: "Keyword",
60 hash: "value",
61 render: ({ value }) => value,
62 },
63 ]}
64 items={data}
65 actions={
66 <Button
67 actionType="destructive"
68 variant="secondary"
69 iconLeft={<DeleteIcon />}
70 disabled={selectedKeywordIds.length === 0}
71 onClick={async () => {
72 await deleteKeywords({
73 ids: selectedKeywordIds,
74 });
75 setSelectedKeywordIds([]);
76 }}
77 >
78 Delete
79 </Button>
80 }
81 emptyComponent={<Text marginTop="medium">No search keywords - start by adding one above!</Text>}
82 />
83 )}
84 </Panel>
85 </>
86 );
87}
88
89const ErrorMessage = ({ title, error }: { title: string; error: Error }) => {
90 return (
91 <Message
92 type="error"
93 header={title}
94 messages={[
95 {
96 text: error.toString(),
97 },
98 ]}
99 marginBottom="medium"
100 />
101 );
102};
1import { Box, Panel, Text, StatefulTable, Form, FormGroup, Input, Button, ProgressCircle, Message } from "@bigcommerce/big-design";
2import { DeleteIcon } from "@bigcommerce/big-design-icons";
3import { useFindMany, useActionForm, useBulkAction } from "@gadgetinc/react";
4import { useState } from "react";
5import { api } from "../api";
6
7export default function () {
8 const [selectedKeywordIds, setSelectedKeywordIds] = useState<string[]>([]);
9
10 // a useFindMany hook to fetch search keyword data
11 const [{ data, fetching, error }] = useFindMany(api.searchKeyword);
12
13 // the useAction hook is used for deleting existing keywords
14 const [{ error: deleteKeywordsError }, deleteKeywords] = useBulkAction(api.searchKeyword.bulkDelete);
15
16 // useActionForm used to manage form state and submission for creating new keywords
17 const { submit, register, reset, error: createError, formState } = useActionForm(api.searchKeyword.create);
18
19 return (
20 <>
21 <Panel>
22 {createError && <ErrorMessage title="Error adding keyword" error={createError} />}
23 <Form
24 onSubmit={async (event) => {
25 event.preventDefault();
26 await submit();
27 reset();
28 }}
29 >
30 <FormGroup>
31 <Input
32 description="Enter a new product search keyword"
33 label="Add search keywords"
34 required
35 {...register("value")}
36 autoComplete="off"
37 />
38 </FormGroup>
39 <Box marginTop="xxLarge">
40 <Button type="submit" disabled={formState.isSubmitting}>
41 Add keyword
42 </Button>
43 </Box>
44 </Form>
45 </Panel>
46 <Panel description="Current search keywords">
47 {fetching && <ProgressCircle size="large" />}
48 {error && <ErrorMessage title="Error reading keywords" error={error} />}
49 {deleteKeywordsError && <ErrorMessage title="Error removing keyword" error={deleteKeywordsError} />}
50 {data && (
51 <StatefulTable
52 stickyHeader
53 pagination
54 itemName="search keywords"
55 selectable
56 onSelectionChange={(value) => setSelectedKeywordIds(value.map((v) => v.id))}
57 columns={[
58 {
59 header: "Keyword",
60 hash: "value",
61 render: ({ value }) => value,
62 },
63 ]}
64 items={data}
65 actions={
66 <Button
67 actionType="destructive"
68 variant="secondary"
69 iconLeft={<DeleteIcon />}
70 disabled={selectedKeywordIds.length === 0}
71 onClick={async () => {
72 await deleteKeywords({
73 ids: selectedKeywordIds,
74 });
75 setSelectedKeywordIds([]);
76 }}
77 >
78 Delete
79 </Button>
80 }
81 emptyComponent={<Text marginTop="medium">No search keywords - start by adding one above!</Text>}
82 />
83 )}
84 </Panel>
85 </>
86 );
87}
88
89const ErrorMessage = ({ title, error }: { title: string; error: Error }) => {
90 return (
91 <Message
92 type="error"
93 header={title}
94 messages={[
95 {
96 text: error.toString(),
97 },
98 ]}
99 marginBottom="medium"
100 />
101 );
102};
@gadgetinc/react hooks

Gadget provides the @gadgetinc/react library which contains useful hooks and tools for building React frontends. The useFindMany, useAction, and useActionForm hooks are used to fetch data, call actions, and manage form state, respectively.

Test it out! 

Now we can test our app by going back to our app in the sandbox store control panel and entering some search keywords. As we do this, the keywords will be stored in our Gadget database.

Once one or more keywords have been added, create a new product in your BigCommerce store and add one or more of the stored keywords to the product description. The keywords should be written back to the product in BigCommerce! You will need to refresh the product page in BigCommerce to see the changes.

Congrats! You have just built a full-stack, single-click app for BigCommerce in Gadget!

Step 7 (Optional): Sync historical product data from BigCommerce 

Our app works great for new or updated products, but what about the products that were already in the store before we installed the app? We can sync historical product data from BigCommerce to our Gadget database to ensure that all products have search keywords.

The bigcommerce/store model has an install.js action that runs when the app is installed. We can use this action to fetch all products from BigCommerce and enqueue a background action to create them in Gadget.

  1. Add the following code to api/models/bigcommerce/store/install.js:
api/models/bigcommerce/store/install.js
JavaScript
1import { ActionOptions, applyParams, save } from "gadget-server";
2
3export const run: ActionRun = async ({ params, record }) => {
4 applyParams(params, record);
5 await save(record);
6};
7
8export const onSuccess: ActionOnSuccess = async ({ api, connections }) => {
9 // set the batch size to 50, process 50 products at a time
10 const BATCH_SIZE = 50;
11
12 const bigcommerce = connections.bigcommerce.current!;
13 // use the API client to fetch all products, and return
14 const products = await bigcommerce.v3.list(`/catalog/products`);
15
16 // get the current store from the database
17 const store = await api.bigcommerce.store.findByStoreHash(
18 connections.bigcommerce.currentStoreHash!,
19 {
20 // only read the id field
21 select: { id: true },
22 }
23 );
24
25 const productPayload = [];
26 // use a for await loop to iterate over the AsyncIterables, add to an array
27 for await (const product of products) {
28 productPayload.push({
29 bigcommerceId: product.id,
30 name: product.name,
31 description: product.description,
32 searchKeywords: product.search_keywords,
33 store: {
34 _link: store.id,
35 },
36 // use the upsert meta action to avoid creating duplicates
37 on: ["bigcommerceId", "store"],
38 });
39
40 // enqueue 80 actions at a time
41 if (productPayload.length >= BATCH_SIZE) {
42 const section = productPayload.splice(0, BATCH_SIZE);
43 // bulk enqueue create action
44 await api.enqueue(api.bigcommerce.product.bulkUpsert, section, {
45 queue: { name: "product-sync" },
46 });
47 }
48 }
49
50 // enqueue any remaining products
51 await api.enqueue(api.bigcommerce.product.bulkUpsert, productPayload, {
52 queue: { name: "product-sync" },
53 });
54};
55
56export const options: ActionOptions = {
57 actionType: "create",
58 // 15 minute timeout for the sync
59 timeoutMS: 900000,
60};
1import { ActionOptions, applyParams, save } from "gadget-server";
2
3export const run: ActionRun = async ({ params, record }) => {
4 applyParams(params, record);
5 await save(record);
6};
7
8export const onSuccess: ActionOnSuccess = async ({ api, connections }) => {
9 // set the batch size to 50, process 50 products at a time
10 const BATCH_SIZE = 50;
11
12 const bigcommerce = connections.bigcommerce.current!;
13 // use the API client to fetch all products, and return
14 const products = await bigcommerce.v3.list(`/catalog/products`);
15
16 // get the current store from the database
17 const store = await api.bigcommerce.store.findByStoreHash(
18 connections.bigcommerce.currentStoreHash!,
19 {
20 // only read the id field
21 select: { id: true },
22 }
23 );
24
25 const productPayload = [];
26 // use a for await loop to iterate over the AsyncIterables, add to an array
27 for await (const product of products) {
28 productPayload.push({
29 bigcommerceId: product.id,
30 name: product.name,
31 description: product.description,
32 searchKeywords: product.search_keywords,
33 store: {
34 _link: store.id,
35 },
36 // use the upsert meta action to avoid creating duplicates
37 on: ["bigcommerceId", "store"],
38 });
39
40 // enqueue 80 actions at a time
41 if (productPayload.length >= BATCH_SIZE) {
42 const section = productPayload.splice(0, BATCH_SIZE);
43 // bulk enqueue create action
44 await api.enqueue(api.bigcommerce.product.bulkUpsert, section, {
45 queue: { name: "product-sync" },
46 });
47 }
48 }
49
50 // enqueue any remaining products
51 await api.enqueue(api.bigcommerce.product.bulkUpsert, productPayload, {
52 queue: { name: "product-sync" },
53 });
54};
55
56export const options: ActionOptions = {
57 actionType: "create",
58 // 15 minute timeout for the sync
59 timeoutMS: 900000,
60};

Now when you install your app on a sandbox store, all products will be synced to your Gadget database, and search keywords will be added to the products in BigCommerce!

To test this code out, you can:

  1. Uninstall your app from your sandbox store.
  2. In the Gadget command palette, run Bulk reset model data and uncheck the searchKeyword model so that your searchKeyword records are not deleted!
  3. Reinstall your app on your sandbox store.

Next steps 

Was this page helpful?