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.
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?
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.
- Create a new Gadget app at gadget.new, select the BigCommerce app type, and give your app a name.
- Click the Connect to BigCommerce button on your app's home page.
- Create a new BigCommerce app in the BigCommerce Developer Portal.
- Copy the Auth callback URL and Load callback URL from Gadget to your BigCommerce app.
- Select the Products Modify OAuth scope and click Update & Close in the BigCommerce app.
- 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.
- In your BigCommerce sandbox store, navigate to Apps → My Draft Apps, hover over your newly added app, click Learn more.
- 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.
- Right-click on the
api/models/bigcommerce
directory in the Gadget file tree and select Add model. - Name the model
product
and add the following fields and validations:
Field name | Field type | Validations |
---|---|---|
bigcommerceId | number | Uniqueness, Required |
name | string | Required |
description | string | |
searchKeywords | string | |
store | belongs to | Required |
type | enum (with options: digital & physical) | Required |
weight | number | Required |
price | number | Required |
- For the
store
field, select thebigcommerce/store
model as the parent model, so thatbigcommerce/store
has manybigcommerce/product
.
- For the
type
field, add the following options:physical
anddigital
.
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.
- Click the + button next to
api/models
to create another new model. (Note: this will create a new model outside of thebigcommerce
namespace.) - Name the model
searchKeyword
and give it the following field and validations:
Field name | Field type | Validations |
---|---|---|
value | string | Uniqueness, 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.
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.
- Click the + button next to
api/actions
and enterbigcommerce/handleProductWebhooks.js
. This creates abigcommerce
namespace folder and our new action. - Click the + button in the action's Triggers card and select BigCommerce.
- Select the
store/product/created
,store/product/updated
, andstore/product/deleted
webhook scopes. - (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.
- Paste the following code in
api/actions/bigcommerce/handleProductWebhooks.js
:
1import { ActionOptions } from "gadget-server";23export 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 }78 // handle deletes early, don't need to query BigCommerce, just need to remove data from Gadget9 if (trigger.scope === "store/product/deleted") {10 // see if product exists in database11 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 it17 await api.bigcommerce.product.delete(productRecordToDelete.id);18 }19 return;20 }2122 // get the BigCommerce API client for the current store23 const bigcommerce = connections.bigcommerce.current!;2425 // fetch the product data26 const product = await bigcommerce.v3.get("/catalog/products/{product_id}", {27 path: {28 product_id: params.id,29 },30 });3132 if (product) {33 // split out fields we are storing in database34 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 relationship41 _link: connections.bigcommerce.currentStoreId,42 },43 type: product.type,44 price: product.price,45 weight: product.weight,46 };4748 // a switch statement to handle different product webhook topics49 // use the trigger parameter to access the webhook scope50 switch (trigger.scope) {51 case "store/product/created":52 // add product to database53 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 identifier57 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};6768export 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";23export 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 }78 // handle deletes early, don't need to query BigCommerce, just need to remove data from Gadget9 if (trigger.scope === "store/product/deleted") {10 // see if product exists in database11 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 it17 await api.bigcommerce.product.delete(productRecordToDelete.id);18 }19 return;20 }2122 // get the BigCommerce API client for the current store23 const bigcommerce = connections.bigcommerce.current!;2425 // fetch the product data26 const product = await bigcommerce.v3.get("/catalog/products/{product_id}", {27 path: {28 product_id: params.id,29 },30 });3132 if (product) {33 // split out fields we are storing in database34 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 relationship41 _link: connections.bigcommerce.currentStoreId,42 },43 type: product.type,44 price: product.price,45 weight: product.weight,46 };4748 // a switch statement to handle different product webhook topics49 // use the trigger parameter to access the webhook scope50 switch (trigger.scope) {51 case "store/product/created":52 // add product to database53 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 identifier57 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};6768export 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.
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 payloadapi
to call our app's API and interact with our databaseconnections
to get the BigCommerce API clienttrigger
to read the webhook topiclogger
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.
- Create a
utils.js
file in theapi/models/bigcommerce/product
directory. - Add the following code to
utils.js
:
1import { api, logger, connections } from "gadget-server";23export 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 description14 const descriptionWords = [...new Set(record.description.match(/\w+(?:'\w+)*/g))];15 // get array of entered search keywords16 const savedKeywords = (await api.searchKeyword.findMany()).map(17 (searchKeyword) => searchKeyword.value18 );19 // get the final list of keywords to be used for the product20 let searchKeywords = [21 ...new Set(descriptionWords.filter((tag) => savedKeywords.includes(tag))),22 ];2324 // concatenate with existing searchKeywords, using a Set to remove duplicates25 if (record.searchKeywords) {26 searchKeywords = Array.from(27 new Set(record.searchKeywords.split(",").concat(searchKeywords))28 );29 }3031 logger.info(32 { descriptionWords, savedKeywords, searchKeywords },33 "keyword and description info"34 );3536 // get the storeHash for the current product37 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 store41 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";23export 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 description14 const descriptionWords = [...new Set(record.description.match(/\w+(?:'\w+)*/g))];15 // get array of entered search keywords16 const savedKeywords = (await api.searchKeyword.findMany()).map(17 (searchKeyword) => searchKeyword.value18 );19 // get the final list of keywords to be used for the product20 let searchKeywords = [21 ...new Set(descriptionWords.filter((tag) => savedKeywords.includes(tag))),22 ];2324 // concatenate with existing searchKeywords, using a Set to remove duplicates25 if (record.searchKeywords) {26 searchKeywords = Array.from(27 new Set(record.searchKeywords.split(",").concat(searchKeywords))28 );29 }3031 logger.info(32 { descriptionWords, savedKeywords, searchKeywords },33 "keyword and description info"34 );3536 // get the storeHash for the current product37 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 store41 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.
- Update
api/models/bigcommerce/product/actions/create.js
:
1import { applyParams, save, ActionOptions } from "gadget-server";2import { getKeywords } from "../utils";34export const run: ActionRun = async ({ params, record }) => {5 applyParams(params, record);6 await save(record);7};89export 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};1819export const options: ActionOptions = {20 actionType: "create",21};
1import { applyParams, save, ActionOptions } from "gadget-server";2import { getKeywords } from "../utils";34export const run: ActionRun = async ({ params, record }) => {5 applyParams(params, record);6 await save(record);7};89export 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};1819export const options: ActionOptions = {20 actionType: "create",21};
- Update
api/models/bigcommerce/product/actions/update.js
:
1import { ActionOptions, applyParams, save } from "gadget-server";2import { getKeywords } from "../utils";34export const run: ActionRun = async ({ params, record }) => {5 applyParams(params, record);6 await save(record);7};89export 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};2324export const options: ActionOptions = {25 actionType: "update",26};
1import { ActionOptions, applyParams, save } from "gadget-server";2import { getKeywords } from "../utils";34export const run: ActionRun = async ({ params, record }) => {5 applyParams(params, record);6 await save(record);7};89export 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};2324export 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.
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.
- Navigate to the
accessControl/permissions
page. - Grant the
bigcommerce-app-users
role access to thesearchKeyword/
model'sread
,create
, anddelete
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.
- Replace the code in
web/routes/index.jsx
with the following:
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";67export default function () {8 const [selectedKeywordIds, setSelectedKeywordIds] = useState<string[]>([]);910 // a useFindMany hook to fetch search keyword data11 const [{ data, fetching, error }] = useFindMany(api.searchKeyword);1213 // the useAction hook is used for deleting existing keywords14 const [{ error: deleteKeywordsError }, deleteKeywords] = useBulkAction(api.searchKeyword.bulkDelete);1516 // useActionForm used to manage form state and submission for creating new keywords17 const { submit, register, reset, error: createError, formState } = useActionForm(api.searchKeyword.create);1819 return (20 <>21 <Panel>22 {createError && <ErrorMessage title="Error adding keyword" error={createError} />}23 <Form24 onSubmit={async (event) => {25 event.preventDefault();26 await submit();27 reset();28 }}29 >30 <FormGroup>31 <Input32 description="Enter a new product search keyword"33 label="Add search keywords"34 required35 {...register("value")}36 autoComplete="off"37 />38 </FormGroup>39 <Box marginTop="xxLarge">40 <Button type="submit" disabled={formState.isSubmitting}>41 Add keyword42 </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 <StatefulTable52 stickyHeader53 pagination54 itemName="search keywords"55 selectable56 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 <Button67 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 Delete79 </Button>80 }81 emptyComponent={<Text marginTop="medium">No search keywords - start by adding one above!</Text>}82 />83 )}84 </Panel>85 </>86 );87}8889const ErrorMessage = ({ title, error }: { title: string; error: Error }) => {90 return (91 <Message92 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";67export default function () {8 const [selectedKeywordIds, setSelectedKeywordIds] = useState<string[]>([]);910 // a useFindMany hook to fetch search keyword data11 const [{ data, fetching, error }] = useFindMany(api.searchKeyword);1213 // the useAction hook is used for deleting existing keywords14 const [{ error: deleteKeywordsError }, deleteKeywords] = useBulkAction(api.searchKeyword.bulkDelete);1516 // useActionForm used to manage form state and submission for creating new keywords17 const { submit, register, reset, error: createError, formState } = useActionForm(api.searchKeyword.create);1819 return (20 <>21 <Panel>22 {createError && <ErrorMessage title="Error adding keyword" error={createError} />}23 <Form24 onSubmit={async (event) => {25 event.preventDefault();26 await submit();27 reset();28 }}29 >30 <FormGroup>31 <Input32 description="Enter a new product search keyword"33 label="Add search keywords"34 required35 {...register("value")}36 autoComplete="off"37 />38 </FormGroup>39 <Box marginTop="xxLarge">40 <Button type="submit" disabled={formState.isSubmitting}>41 Add keyword42 </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 <StatefulTable52 stickyHeader53 pagination54 itemName="search keywords"55 selectable56 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 <Button67 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 Delete79 </Button>80 }81 emptyComponent={<Text marginTop="medium">No search keywords - start by adding one above!</Text>}82 />83 )}84 </Panel>85 </>86 );87}8889const ErrorMessage = ({ title, error }: { title: string; error: Error }) => {90 return (91 <Message92 type="error"93 header={title}94 messages={[95 {96 text: error.toString(),97 },98 ]}99 marginBottom="medium"100 />101 );102};
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.
- Add the following code to
api/models/bigcommerce/store/install.js
:
1import { ActionOptions, applyParams, save } from "gadget-server";23export const run: ActionRun = async ({ params, record }) => {4 applyParams(params, record);5 await save(record);6};78export const onSuccess: ActionOnSuccess = async ({ api, connections }) => {9 // set the batch size to 50, process 50 products at a time10 const BATCH_SIZE = 50;1112 const bigcommerce = connections.bigcommerce.current!;13 // use the API client to fetch all products, and return14 const products = await bigcommerce.v3.list(`/catalog/products`);1516 // get the current store from the database17 const store = await api.bigcommerce.store.findByStoreHash(18 connections.bigcommerce.currentStoreHash!,19 {20 // only read the id field21 select: { id: true },22 }23 );2425 const productPayload = [];26 // use a for await loop to iterate over the AsyncIterables, add to an array27 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 duplicates37 on: ["bigcommerceId", "store"],38 });3940 // enqueue 80 actions at a time41 if (productPayload.length >= BATCH_SIZE) {42 const section = productPayload.splice(0, BATCH_SIZE);43 // bulk enqueue create action44 await api.enqueue(api.bigcommerce.product.bulkUpsert, section, {45 queue: { name: "product-sync" },46 });47 }48 }4950 // enqueue any remaining products51 await api.enqueue(api.bigcommerce.product.bulkUpsert, productPayload, {52 queue: { name: "product-sync" },53 });54};5556export const options: ActionOptions = {57 actionType: "create",58 // 15 minute timeout for the sync59 timeoutMS: 900000,60};
1import { ActionOptions, applyParams, save } from "gadget-server";23export const run: ActionRun = async ({ params, record }) => {4 applyParams(params, record);5 await save(record);6};78export const onSuccess: ActionOnSuccess = async ({ api, connections }) => {9 // set the batch size to 50, process 50 products at a time10 const BATCH_SIZE = 50;1112 const bigcommerce = connections.bigcommerce.current!;13 // use the API client to fetch all products, and return14 const products = await bigcommerce.v3.list(`/catalog/products`);1516 // get the current store from the database17 const store = await api.bigcommerce.store.findByStoreHash(18 connections.bigcommerce.currentStoreHash!,19 {20 // only read the id field21 select: { id: true },22 }23 );2425 const productPayload = [];26 // use a for await loop to iterate over the AsyncIterables, add to an array27 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 duplicates37 on: ["bigcommerceId", "store"],38 });3940 // enqueue 80 actions at a time41 if (productPayload.length >= BATCH_SIZE) {42 const section = productPayload.splice(0, BATCH_SIZE);43 // bulk enqueue create action44 await api.enqueue(api.bigcommerce.product.bulkUpsert, section, {45 queue: { name: "product-sync" },46 });47 }48 }4950 // enqueue any remaining products51 await api.enqueue(api.bigcommerce.product.bulkUpsert, productPayload, {52 queue: { name: "product-sync" },53 });54};5556export const options: ActionOptions = {57 actionType: "create",58 // 15 minute timeout for the sync59 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:
- Uninstall your app from your sandbox store.
- In the Gadget command palette, run Bulk reset model data and uncheck the searchKeyword model so that your
searchKeyword
records are not deleted! - Reinstall your app on your sandbox store.
Next steps
Join Gadget's developer community on Discord
Learn more about working with BigCommerce data
Build single-click app frontends and from building with the BigDesign library