parse Gidgear
gear
Parses Shopify Global ID (GID) and returns the resource type and ID.
Anchor to parseGid-parametersParameters
- stringrequired
A shopify GID (string)
Anchor to parseGid-returnsReturns
ShopifyGid
Pick<URL, 'search' | 'searchParams' | 'hash'> & {
id: string;
resource: string | null;
resourceId: string | null;
}
ParseGidGeneratedType
Parses global id (gid) and returns the resource type and id.
- gid
A shopify GID (string)
string
ShopifyGid
export function parseGid(gid: string | undefined): ShopifyGid {
const defaultReturn: ShopifyGid = {
id: '',
resource: null,
resourceId: null,
search: '',
searchParams: new URLSearchParams(),
hash: '',
};
if (typeof gid !== 'string') {
return defaultReturn;
}
try {
const {search, searchParams, pathname, hash} = new URL(gid);
const pathnameParts = pathname.split('/');
const lastPathnamePart = pathnameParts[pathnameParts.length - 1];
const resourcePart = pathnameParts[pathnameParts.length - 2];
if (!lastPathnamePart || !resourcePart) {
return defaultReturn;
}
const id = `${lastPathnamePart}${search}${hash}` || '';
const resourceId = lastPathnamePart || null;
const resource = resourcePart ?? null;
return {id, resource, resourceId, search, searchParams, hash};
} catch {
return defaultReturn;
}
}
ShopifyGid
Pick<URL, 'search' | 'searchParams' | 'hash'> & {
id: string;
resource: string | null;
resourceId: string | null;
}
Was this section helpful?
Example code
JavaScript
import {parseGid} from '@shopify/hydrogen-react';
const {id, resource} = parseGid('gid://shopify/Order/123');
console.log(id); // 123
console.log(resource); // Order
examples
Example code
description
I am the default example
JavaScript
import {parseGid} from '@shopify/hydrogen-react'; const {id, resource} = parseGid('gid://shopify/Order/123'); console.log(id); // 123 console.log(resource); // Order