UNPKG

@shopify/hydrogen-react

Version:

React components, hooks, and utilities for creating custom Shopify storefronts

1 lines 2.07 kB
{"version":3,"file":"flatten-connection.mjs","sources":["../../src/flatten-connection.ts"],"sourcesContent":["import type {PartialDeep} from 'type-fest';\n\n/**\n * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](https://shopify.dev/api/storefront/reference/products/product)) into a flat array of nodes.\n * The utility works with either `nodes` or `edges.node`.\n *\n * If `connection` is null or undefined, will return an empty array instead in production. In development, an error will be thrown.\n */\nexport function flattenConnection<T>(\n connection?: PartialDeep<GraphQLConnection<T>, {recurseIntoArrays: true}>\n): PartialDeep<T, {recurseIntoArrays: true}>[] {\n if (!connection) {\n const noConnectionErr = `flattenConnection(): needs a 'connection' to flatten, but received '${connection}' instead`;\n if (__HYDROGEN_DEV__) {\n throw new Error(noConnectionErr);\n } else {\n console.error(noConnectionErr);\n return [];\n }\n }\n\n if (connection.nodes) {\n return connection.nodes as PartialDeep<T, {recurseIntoArrays: true}>[];\n }\n\n if (connection.edges) {\n return connection.edges.map((edge) => {\n if (!edge?.node) {\n throw new Error('Connection edges must contain nodes');\n }\n return edge.node;\n });\n }\n\n if (__HYDROGEN_DEV__) {\n console.warn(\n `The connection did not contain either \"nodes\" or \"edges.node\". A empty array will be returned in its place.`\n );\n }\n\n return [];\n}\n\ninterface GraphQLConnection<T> {\n edges?: {node: T}[];\n nodes?: T[];\n}\n"],"names":[],"mappings":"AAQO,SAAS,kBACd,YAC6C;AAC7C,MAAI,CAAC,YAAY;AACf,UAAM,kBAAkB,uEAAuE;AACzE;AACd,YAAA,IAAI,MAAM,eAAe;AAAA,IAIjC;AAAA,EACF;AAEA,MAAI,WAAW,OAAO;AACpB,WAAO,WAAW;AAAA,EACpB;AAEA,MAAI,WAAW,OAAO;AACpB,WAAO,WAAW,MAAM,IAAI,CAAC,SAAS;AAChC,UAAA,EAAC,6BAAM,OAAM;AACT,cAAA,IAAI,MAAM,qCAAqC;AAAA,MACvD;AACA,aAAO,KAAK;AAAA,IAAA,CACb;AAAA,EACH;AAEsB;AACZ,YAAA;AAAA,MACN;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO;AACT;"}