here is my index.js code
import scriptTags from â./middleware/scriptTags.jsâ;
import shopify from â./shopify.jsâ;
const app = express();
app.post(â/api/installâ, async (_req, res) => {
console.log(res.locals.shopify.session.shop);
});
const sessionId= await shopify.api.session.getOfflineId(âtest.myshopify.comâ);
const session= await shopify.config.sessionStorage.loadSession(sessionId);
const client = new shopify.api.clients.Rest({session});
console.log(client)
const USE_ONLINE_TOKENS = false;
const result=scriptTags(app);
const PORT = parseInt(process.env.BACKEND_PORT || process.env.PORT, 10);
// TODO: There should be provided by env vars
const DEV_INDEX_PATH = ${process.cwd()}/frontend/
;
const PROD_INDEX_PATH = ${process.cwd()}/frontend/dist/
;
const DB_PATH = ${process.cwd()}/database.sqlite
;
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(â,â),
HOST_NAME: process.env.HOST.replace(/https?:///, ââ),
HOST_SCHEME: process.env.HOST.split(â://â)[0],
API_VERSION: LATEST_API_VERSION,
IS_EMBEDDED_APP: true,
// This should be replaced with your preferred storage strategy
// See note below regarding using CustomSessionStorage with this template.
SESSION_STORAGE: new Shopify.Session.SQLiteSessionStorage(DB_PATH),
âŚ(process.env.SHOP_CUSTOM_DOMAIN && {CUSTOM_SHOP_DOMAINS: [process.env.SHOP_CUSTOM_DOMAIN]}),
});
// NOTE: If you choose to implement your own storage strategy using
// Shopify.Session.CustomSessionStorage, you MUST implement the optional
// findSessionsByShopCallback and deleteSessionsCallback methods. These are
// required for the app_installations.js component in this template to
// work properly.
Shopify.Webhooks.Registry.addHandler(âAPP_UNINSTALLEDâ, {
path: â/api/webhooksâ,
webhookHandler: async (_topic, shop, _body) => {
await AppInstallations.delete(shop);
},
});
// The transactions with Shopify will always be marked as test transactions, unless NODE_ENV is production.
// See the ensureBilling helper to learn more about billing in this template.
const BILLING_SETTINGS = {
required: false,
// This is an example configuration that would do a one-time charge for $5 (only USD is currently supported)
// chargeName: âMy Shopify One-Time Chargeâ,
// amount: 5.0,
// currencyCode: âUSDâ,
// interval: BillingInterval.OneTime,
};
// This sets up the mandatory GDPR webhooks. Youâll need to fill in the endpoint
// in the âGDPR mandatory webhooksâ section in the âApp setupâ tab, and customize
// the code when you store customer data.
//
// More details can be found on shopify.dev:
// https://shopify.dev/apps/webhooks/configuration/mandatory-webhooks
setupGDPRWebHooks(â/api/webhooksâ);
// export for test use only
export async function createServer(
root = process.cwd(),
isProd = process.env.NODE_ENV === âproductionâ,
billingSettings = BILLING_SETTINGS
) {
app.get(â/electronicsâ, function (req, res) {
res.send(âThis is the electronics categoryâ);
});
app.get(shopify.config.auth.path, shopify.auth.begin());
app.get(
shopify.config.auth.callbackPath,
shopify.auth.callback(),
shopify.redirectToShopifyOrAppRoot()
);
app.set(âuse-online-tokensâ, USE_ONLINE_TOKENS);
app.use(cookieParser(Shopify.Context.API_SECRET_KEY));
applyAuthMiddleware(app, {
billing: billingSettings,
});
// Do not call app.use(express.json()) before processing webhooks with
// Shopify.Webhooks.Registry.process().
// See https://github.com/Shopify/shopify-api-node/blob/main/docs/usage/webhooks.md#note-regarding-use-of-body-parsers
// for more details.
app.post(â/api/webhooksâ, async (req, res) => {
try {
await Shopify.Webhooks.Registry.process(req, res);
console.log(Webhook processed, returned status code 200
);
} catch (e) {
console.log(Failed to process webhook: ${e.message}
);
if (!res.headersSent) {
res.status(500).send(e.message);
}
}
});
app.get(â/api/shopâ, async (_req, res) => {
console.log(âCalling apiâ)
// Refer to docs: https://shopify.dev/docs/api/admin-rest/2023-01/resources/shop#resource-object
const shopData = await shopify.api.rest.Shop.all({
session: res.locals.shopify.session,
});
res.status(200).send(shopData);
});
// All endpoints after this point will require an active session
app.use(
â/api/*â,
verifyRequest(app, {
billing: billingSettings,
})
);
app.get(â/api/products/countâ, async (req, res) => {
const session = await Shopify.Utils.loadCurrentSession(
req,
res,
app.get(âuse-online-tokensâ)
);
const { Product } = await import(
@shopify/shopify-api/dist/rest-resources/${Shopify.Context.API_VERSION}/index.js
);
const countData = await Product.count({ session });
res.status(200).send(countData);
});
app.get(â/api/products/createâ, async (req, res) => {
console.log(ââŚproduct creatorâ)
const session = await Shopify.Utils.loadCurrentSession(
req,
res,
app.get(âuse-online-tokensâ)
);
let status = 200;
let error = null;
try {
await productCreator(session);
} catch (e) {
console.log(Failed to process products/create: ${e.message}
);
status = 500;
error = e.message;
}
res.status(status).send({ success: status === 200, error });
});
// All endpoints after this point will have access to a request.body
// attribute, as a result of the express.json() middleware
app.use(express.json());
app.use((req, res, next) => {
const shop = Shopify.Utils.sanitizeShop(req.query.shop);
if (Shopify.Context.IS_EMBEDDED_APP && shop) {
res.setHeader(
âContent-Security-Policyâ,
frame-ancestors https://${encodeURIComponent( shop )} [https://admin.shopify.com](https://admin.shopify.com);
);
} else {
res.setHeader(âContent-Security-Policyâ, frame-ancestors 'none';
);
}
next();
});
if (isProd) {
const compression = await import(âcompressionâ).then(
({ default: fn }) => fn
);
const serveStatic = await import(âserve-staticâ).then(
({ default: fn }) => fn
);
app.use(compression());
app.use(serveStatic(PROD_INDEX_PATH, { index: false }));
}
app.use(â/*â, async (req, res, next) => {
if (typeof req.query.shop !== âstringâ) {
res.status(500);
return res.send(âNo shop providedâ);
}
const shop = Shopify.Utils.sanitizeShop(req.query.shop);
console.log("Shop name is ")
console.log(shop)
const appInstalled = await AppInstallations.includes(shop);
if (!appInstalled && !req.originalUrl.match(/^/exitiframe/i)) {
return redirectToAuth(req, res, app);
}
if (Shopify.Context.IS_EMBEDDED_APP && req.query.embedded !== â1â) {
const embeddedUrl = Shopify.Utils.getEmbeddedAppUrl(req);
return res.redirect(embeddedUrl + req.path);
}
const htmlFile = join(
isProd ? PROD_INDEX_PATH : DEV_INDEX_PATH,
âindex.htmlâ
);
return res
.status(200)
.set(âContent-Typeâ, âtext/htmlâ)
.send(readFileSync(htmlFile));
});
return { app };
}
createServer().then(({ app }) => app.listen(PORT));