Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: search by urlkey #11

Merged
merged 3 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ export async function resolveConfig(ctx, tenant, overrides = {}) {
);

// merge configs
return {
/** @type {Config} */
const resolved = {
...paths.reduce((conf, key) => ({
...conf,
...confMap[key],
Expand All @@ -70,4 +71,13 @@ export async function resolveConfig(ctx, tenant, overrides = {}) {
}),
...overrides,
};

// ensure validity
// TODO: make this more robust
if (!resolved.pageType) {
ctx.log.warn('invalid config for tenant (missing pageType)', tenant);
return null;
}

return resolved;
}
60 changes: 52 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import { errorResponse, errorWithResponse, makeContext } from './util.js';
import getProductQueryCS, { adapter } from './queries/cs-product.js';
import getProductQueryCore from './queries/core-product.js';
import getProductSKUQuery from './queries/core-product-sku.js';
import HTML_TEMPLATE from './templates/html.js';
import { resolveConfig } from './config.js';

Expand Down Expand Up @@ -79,7 +80,7 @@ async function fetchProductCore(opt, config) {

const json = await resp.json();
try {
const [product] = json.data.products;
const [product] = json.data.products.items;
if (!product) {
throw errorWithResponse(404, 'could not find product', json.errors);
}
Expand All @@ -90,14 +91,57 @@ async function fetchProductCore(opt, config) {
}
}

/**
* @param {string} urlkey
* @param {Config} config
*/
async function lookupProductSKU(urlkey, config) {
const query = getProductSKUQuery({ urlkey });
const resp = await fetch(`${config.coreEndpoint}?query=${encodeURIComponent(query)}`, {
headers: {
origin: 'https://api.adobecommerce.live',
'x-api-key': config.apiKey,
'Magento-Environment-Id': config.magentoEnvironmentId,
'Magento-Website-Code': config.magentoWebsiteCode,
'Magento-Store-View-Code': config.magentoStoreViewCode,
},
});
if (!resp.ok) {
console.warn('failed to fetch product sku: ', resp.status, resp.statusText);
throw errorWithResponse(resp.status, 'failed to fetch product sku');
}

const json = await resp.json();
try {
const [product] = json.data.products.items;
if (!product) {
throw errorWithResponse(404, 'could not find product sku', json.errors);
}
return product.sku;
} catch (e) {
console.error('failed to parse product sku: ', e);
throw errorWithResponse(500, 'failed to parse product sku response');
}
}

/**
* @param {Context} ctx
* @param {Config} config
*/
async function handlePDPRequest(ctx, config) {
const { sku, urlkey } = config.params;
const { urlkey } = config.params;
let { sku } = config.params;

if (!sku && !urlkey) {
return errorResponse(404, 'missing sku or urlkey');
} else if (!sku && !config.coreEndpoint) {
return errorResponse(400, 'missing sku and coreEndpoint');
}

if (!sku) {
// lookup sku by urlkey with core
// TODO: test if livesearch if enabled
sku = await lookupProductSKU(urlkey, config);
}

// const product = await fetchProductCore({ sku }, config);
Expand Down Expand Up @@ -146,13 +190,13 @@ export default {
return errorResponse(404, 'missing route');
}

const overrides = Object.fromEntries(ctx.url.searchParams.entries());
const config = await resolveConfig(ctx, tenant, overrides);
if (!config) {
return errorResponse(404, 'config not found');
}

try {
const overrides = Object.fromEntries(ctx.url.searchParams.entries());
const config = await resolveConfig(ctx, tenant, overrides);
if (!config) {
return errorResponse(404, 'config not found');
}

return handlers[route](ctx, config);
} catch (e) {
if (e.response) {
Expand Down
26 changes: 26 additions & 0 deletions src/queries/core-product-sku.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import { gql } from '../util.js';

/**
* @param {{ urlkey: string; }} param0
*/
export default ({ urlkey }) => gql`{
products(
filter: { url_key: { eq: "${urlkey}" } }
) {
items {
sku
}
}
}`;
1 change: 1 addition & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ declare global {
magentoEnvironmentId: string;
magentoWebsiteCode: string;
magentoStoreViewCode: string;
magentoStoreCode: string;
coreEndpoint: string;
params: Record<string, string>;
}
Expand Down
8 changes: 8 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ ENVIRONMENT = "dev"
[env.ci]
name = "adobe-commerce-api-ci"

kv_namespaces = [
{ binding = "CONFIGS", id = "bb91e12a65a8462282396f32e63406f1", preview_id = "bb91e12a65a8462282396f32e63406f1" }
]

[env.ci.vars]
VERSION = "@@VERSION@@-ci"
ENVIRONMENT = "ci"
Expand All @@ -31,6 +35,10 @@ ENVIRONMENT = "ci"
[env.production]
name = "adobe-commerce-api"

kv_namespaces = [
{ binding = "CONFIGS", id = "bb91e12a65a8462282396f32e63406f1", preview_id = "bb91e12a65a8462282396f32e63406f1" }
]

[env.production.vars]
VERSION = "@@VERSION@@"
ENVIRONMENT = "prod"
Expand Down