Shared Types
Comprehensive TypeScript type definitions for the Haus Storefront Components ecosystem.
Purpose
This library provides a centralized collection of TypeScript types, interfaces, and enums used across the entire Haus Storefront Components ecosystem. It ensures type safety and consistency between all components, hooks, and utilities in the monorepo.
Features
- Error Handling Types: Structured error types for e-commerce operations with error codes and messages
- Utility Types: TypeScript utility types for common transformations (Maybe, WithRequired, RequireAtLeastOne, etc.)
- E-commerce Core Types: Complete type definitions for Products, Variants, Collections, Orders, Customers, and Addresses
- Search & Filtering Types: Comprehensive types for search queries, filters, facets, and sorting
- GraphQL Query Builder Types: Type-safe GraphQL query construction with field selection and variables
- Plugin System Types: Extensible plugin configuration system for customizing storefront behavior
- Component Props Types: Reusable prop types for React components (ChildrenProps, CustomHTMLElement, EcomWidget)
- Enum Definitions: Currency codes, language codes, asset types, logical operators, sort orders, and error codes
Installation
- npm
- Yarn
npm install @haus-storefront-react/shared-types
yarn add @haus-storefront-react/shared-types
Note: This is not a public package. Contact the Haus Tech Team for access.
Types & Interfaces
ErrorResult
Represents a structured error result with error code and message.
type ErrorResult = {
errorCode: ErrorCode
message: string
code?: string
}
GenericEcomError
A union type representing various error sources that can occur in e-commerce operations.
type GenericEcomError = Maybe<
AxiosError | ErrorResult | Error | (Error & { code: string }) | undefined
>
Maybe
Utility type that makes a type nullable.
type Maybe<T> = T | null
Exact
Utility type for strict object matching.
type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }
WithRequired
Utility type that makes specific keys required in an object type.
type WithRequired<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & CustomRequired<T, K>
OneOfType
Utility type for creating union types where exactly one key must be present.
type OneOfType<Obj> = ValueOf<OneOfByKey<Obj>>
RequireAtLeastOne
Utility type that ensures at least one key from a set of keys is present.
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>
}[Keys]
RequireOnlyOne
Utility type that ensures exactly one key from a set of keys is present.
type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Record<Exclude<Keys, K>, undefined>>
}[Keys]
ArrayElement
Utility type that extracts the element type from an array type.
type ArrayElement<A> = A extends readonly (infer T)[] ? T : never
ObtainKeys
Utility type that obtains keys from an object where the value matches a given type.
type ObtainKeys<Obj, Type> = {
[Prop in keyof Obj]: Obj[Prop] extends Type ? Prop : never
}[keyof Obj]
PluginFeatures
Maps plugin feature names to their feature configurations.
type PluginFeatures = Partial<{
[K in PluginFeatureNames]: PluginFeatureMappings[K]
}>
PluginName
Represents a plugin identifier, either a known plugin name or a custom string.
type PluginName = 'packageSize' | 'productPopularity' | 'badges' | 'campaign' | 'elastic' | string
ProviderDataMap
Array of provider data configurations for wrapping React components.
type ProviderDataMap = Array<ProviderData>
IVendurePluginConfig
Configuration interface for Vendure plugins with feature flags, query updates, requests, providers, and settings.
interface IVendurePluginConfig<Features extends PluginFeatures, R, S, T> {
readonly name: PluginName
enabled?: boolean
enableFeatures?: Partial<Record<keyof Features, boolean>> | Partial<Features>
queryUpdates: BuilderQueryUpdates
requests?: R
providers?: ProviderDataMap
settings?: S
setSdk: (sdk: T) => void
setProviders: (providers: ProviderDataMap) => void
setEnabled: (enabled: boolean) => void
setEnableFeatures: (
enableFeatures: Partial<Record<keyof Features, boolean>> | Partial<Features>,
) => void
setQueryUpdates: (queryUpdates: BuilderQueryUpdates) => void
setRequests: (requests: R) => void
setSettings: (settings: S) => void
getSdk: () => T
getProviders: () => ProviderDataMap
getEnabled: () => boolean
getEnabledFeatures: () => Partial<Record<keyof Features, boolean>> | Partial<Features>
getQueryUpdates: () => BuilderQueryUpdates
getRequests: () => R
getSettings: () => S
}
FacetValueFilterType
Filter type configuration for facet values.
type FacetValueFilterType = {
type?: 'facet'
facetCode: string
logicalOperator?: keyof FacetValueFilterInput
}
PriceFilterType
Filter type configuration for price ranges.
type PriceFilterType = {
type: 'price'
}
EnabledFilter
Filter configuration with an optional label.
type EnabledFilter<T = FacetValueFilterType | PriceFilterType> = T & {
label?: string
}
ActiveFilters
Record of active filter values keyed by filter identifier.
type ActiveFilters = Record<string, (string | undefined)[]>
FacetValueFilterInput
Input configuration for filtering by facet values with logical operators.
type FacetValueFilterInput = {
and?: Maybe<string>
or?: Maybe<Array<string>>
not?: Maybe<Array<string>>
}
VariableDefinition
Definition for GraphQL query variables.
interface VariableDefinition {
type: 'String' | 'ID' | 'String!' | 'ID!'
}
FragmentField
GraphQL fragment field definition.
type FragmentField = {
operation: string
fields: Field[]
fragment: boolean
}
Field
Union type for GraphQL field definitions, supporting strings, nested fields, and fragments.
type Field = string | NestedField | FragmentField
NestedField
Record-based structure for nested GraphQL fields.
type NestedField = Record<string, Field[]>
BuilderQuery
Structure for building GraphQL queries with operation, fields, and variables.
interface BuilderQuery<Vars extends Record<string, unknown> = Record<string, unknown>> {
operation: string
fields: Field[]
variables?: Vars
}
ExpectedVariables
Type helper for validating query variables.
type ExpectedVariables<Vars> = {
[K in keyof Vars]: Vars[K] extends { type: string } ? unknown : unknown
}
BuilderQueries
Type for a collection of builder queries.
type BuilderQueries<T = Record<string, BuilderQuery>> = T
BuilderQueryUpdates
Record of query updates keyed by query name.
interface BuilderQueryUpdates {
[key: string]: Pick<BuilderQuery, 'fields'>
}
QueryResponse
Type wrapper for GraphQL query responses.
type QueryResponse<T> = AxiosResponse<T>
SearchInput
Configuration for search queries with term, collections, filters, sorting, and pagination.
interface SearchInput {
term?: Maybe<string>
collectionId?: Maybe<string>
collectionSlug?: Maybe<string>
facetValueIds?: Maybe<Array<string>>
facetValueOperator?: Maybe<LogicalOperator>
facetValueFilters?: Maybe<Array<FacetValueFilterInput>>
groupByProduct?: Maybe<boolean>
inStock?: Maybe<boolean>
sort?: Maybe<SearchResultSortParameter>
take?: Maybe<number>
skip?: Maybe<number>
}
Pagination
Pagination state and navigation controls.
interface Pagination {
isInitialized: boolean
totalItems: number
totalPages: number
currentPage: number
itemsPerPage: number
canGoBack: boolean
canGoForward: boolean
infinitePagination: boolean
nextState: SearchInput
nextPage: () => void
prevPage: () => void
goToPage: (page: number) => void
}
SearchResultSortParameter
Sorting configuration for search results.
interface SearchResultSortParameter {
name?: Maybe<SortOrder>
price?: Maybe<SortOrder>
popularity?: Maybe<SortOrder>
}
Filters
Filter state and setter function.
interface Filters {
sort: Maybe<SearchResultSortParameter> | undefined
setSort: (sort: SearchResultSortParameter) => void
}
StringOperators
String comparison operators for filtering.
type StringOperators = {
contains?: Maybe<string>
eq?: Maybe<string>
in?: Maybe<Array<string>>
isNull?: Maybe<boolean>
notContains?: Maybe<string>
notEq?: Maybe<string>
notIn?: Maybe<Array<string>>
regex?: Maybe<string>
}
BooleanOperators
Boolean comparison operators for filtering.
type BooleanOperators = {
eq?: Maybe<boolean>
isNull?: Maybe<boolean>
}
DateRange
Date range with start and end dates.
type DateRange = {
end: string
start: string
}
DateOperators
Date comparison operators for filtering.
type DateOperators = {
after?: Maybe<string>
before?: Maybe<string>
between?: Maybe<DateRange>
eq?: Maybe<string>
isNull?: Maybe<boolean>
}
IdOperators
ID comparison operators for filtering.
type IdOperators = {
eq?: Maybe<string>
in?: Maybe<Array<string>>
isNull?: Maybe<boolean>
notEq?: Maybe<string>
notIn?: Maybe<Array<string>>
}
NumberRange
Numeric range with start and end values.
type NumberRange = {
end: number
start: number
}
NumberOperators
Numeric comparison operators for filtering.
type NumberOperators = {
between?: Maybe<NumberRange>
eq?: Maybe<number>
gt?: Maybe<number>
gte?: Maybe<number>
isNull?: Maybe<boolean>
lt?: Maybe<number>
lte?: Maybe<number>
}
Loading
Loading state map for multiple loading operations.
type Loading<T extends keyof LoadingMap> = Record<T, boolean>
ChildrenProps
Flexible children prop type supporting functions, React nodes, or JSX elements.
type ChildrenProps<ChildProps = object | null | undefined> =
| ((props: ChildProps) => ReactNode | JSX.Element)
| ReactNode
| JSX.Element
CustomHTMLElement
HTML element props with optional wrapper tag support, omitting children.
type CustomHTMLElement<T = HTMLOrSVGElement, U = object> = Omit<HTMLAttributes<T>, 'children'> & {
wrapperTag?: keyof JSX.IntrinsicElements | typeof React.Fragment
} & U
ClassNamesProps
Component props with class name mapping support.
type ClassNamesProps<T = object> = {
classNames?: Record<string, string>
} & T
EcomWidget
E-commerce widget props extending HTML attributes with slot class names support.
type EcomWidget = HTMLAttributes<HTMLElement> & {
slotClassNames?: ClassNamesProps | Record<string, ClassNamesProps>
}
PriceRange
Price range with minimum and maximum values.
type PriceRange = {
max: number
min: number
}
SinglePrice
Single price value.
type SinglePrice = {
value: number
}
Price
Union type for price values, supporting ranges, single values, or numbers.
type Price = PriceRange | SinglePrice | number
SearchResultAsset
Asset information for search results.
interface SearchResultAsset {
id: string
preview: string
}
FilterInputs
Collection of facet value filter inputs.
interface FilterInputs {
filters: FacetValueFilterInput[]
}
SearchResult
Individual search result item with product and variant information.
interface SearchResult {
collectionIds: Array<string>
currencyCode: CurrencyCode
description: string
facetIds: Array<string>
facetValueIds: Array<string>
inStock: boolean
price: Price
priceWithTax: Price
productAsset?: Maybe<SearchResultAsset>
productId: string
productName: string
productVariantAsset?: Maybe<SearchResultAsset>
productVariantId: string
productVariantName: string
score: number
sku: string
slug: string
}
CollectionList
Paginated list of collections.
interface CollectionList {
items: Array<Collection>
totalItems: number
}
CollectionResult
Single collection result with count.
interface CollectionResult extends ResponseResult {
collection: Collection
}
FacetValueResult
Single facet value result with count.
interface FacetValueResult extends ResponseResult {
facetValue: FacetValue
}
SearchResponse
Complete search response with items, collections, and facet values.
interface SearchResponse {
collections: Array<CollectionResult>
facetValues: Array<FacetValueResult>
items: Array<SearchResult>
totalItems: number
}
ProductResponse
Response containing product items.
interface ProductResponse {
items: Array<Product>
}
GroupedFacetValues
Facet values grouped by facet code.
interface GroupedFacetValues {
[key: string]: FacetValue[]
}
SearchInputProps
Component props extracted from SearchInput interface.
interface SearchInputProps extends Pick<
SearchInput,
| 'term'
| 'collectionId'
| 'facetValueIds'
| 'facetValueOperator'
| 'facetValueFilters'
| 'groupByProduct'
| 'sort'
| 'take'
| 'skip'
> {}
Node
Base node interface with common fields for all entities.
interface Node<CustomFields = Record<string, unknown>> {
id: string
createdAt: string
updatedAt: string
customFields?: CustomFields
}
Channel
Channel configuration with currency and language settings.
interface Channel extends Node {
availableCurrencyCodes: Array<CurrencyCode>
availableLanguageCodes?: Maybe<Array<LanguageCode>>
code: string
currencyCode: CurrencyCode
defaultCurrencyCode: CurrencyCode
defaultLanguageCode: LanguageCode
pricesIncludeTax: boolean
token: string
trackInventory?: string
updatedAt: string
}
Asset
Media asset with file metadata.
interface Asset extends Node {
name: string
type: AssetType
fileSize: number
mimeType: string
width: number
height: number
source: string
preview: string
}
PaginatedList
Generic paginated list structure.
interface PaginatedList<T = Node> {
items: Array<T>
totalItems: number
}
ProductVariantList
Paginated list of product variants.
interface ProductVariantList extends PaginatedList {
items: Array<ProductVariant>
}
FacetList
Paginated list of facets.
interface FacetList extends PaginatedList {
items: Array<Facet>
}
FacetValueList
Paginated list of facet values.
interface FacetValueList extends PaginatedList {
items: Array<FacetValue>
}
Collection
Product collection with hierarchical structure.
interface Collection extends Node {
assets: Array<Asset>
children?: Maybe<Array<Collection>>
description: string
featuredAsset?: Maybe<Asset>
languageCode?: Maybe<LanguageCode>
name: string
parent?: Maybe<Collection>
parentId: string
productVariants: ProductVariantList
slug: string
}
Facet
Facet with associated values for filtering.
interface Facet extends Node {
code: string
languageCode: LanguageCode
name: string
valueList: FacetValueList
values: Array<FacetValue>
}
FacetValue
Individual facet value for filtering products.
interface FacetValue extends Node {
code: string
facet: Facet
facetId: string
languageCode: LanguageCode
name: string
}
ProductOption
Product option within an option group.
interface ProductOption extends Node {
code: string
group: ProductOptionGroup
groupId: string
languageCode: LanguageCode
name: string
}
ProductOptionGroup
Group of product options (e.g., Size, Color).
interface ProductOptionGroup extends Node {
code: string
languageCode: LanguageCode
name: string
options: Array<ProductOption>
}
BriefProduct
Minimal product information.
interface BriefProduct extends Node {
name: string
slug: string
variants: Array<ProductVariant>
}
Product
Complete product with assets, collections, and variants.
interface Product extends BriefProduct {
assets: Array<Asset>
collections: Array<Collection>
description: string
facetValues: Array<FacetValue>
featuredAsset?: Maybe<Asset>
languageCode: LanguageCode
optionGroups: Array<ProductOptionGroup>
variantList: ProductVariantList
currencyCode: CurrencyCode
}
BriefProductVariant
Minimal product variant information.
interface BriefProductVariant extends Node {
name: string
sku: string
price: Price
priceWithTax: Price
currencyCode: CurrencyCode
stockLevel: string
}
ProductVariant
Complete product variant with all details.
interface ProductVariant extends BriefProductVariant {
product: Product
productId: string
languageCode: LanguageCode
featuredAsset: Asset
assets: Array<Asset>
stockLevel: string
taxRateApplied: number
taxCategory: string
options: Array<ProductOption>
facetValues: Array<FacetValue>
customFields: Record<string, unknown>
}
Country
Country information.
interface Country extends Node {
code: LanguageCode
name: string
type: string
enabled: boolean
}
Address
Customer address with optional fields.
interface Address extends Node {
fullName?: Maybe<string>
company?: Maybe<string>
streetLine1?: Maybe<string>
streetLine2?: Maybe<string>
city?: Maybe<string>
province?: Maybe<string>
postalCode?: Maybe<string>
phoneNumber?: Maybe<string>
defaultShippingAddress?: Maybe<boolean>
defaultBillingAddress?: Maybe<boolean>
country?: Maybe<Country>
}
CreateAddressInput
Input type for creating a new address.
interface CreateAddressInput extends Omit<Address, 'id' | 'createdAt' | 'updatedAt' | 'country'> {
streetLine1: string
countryCode: string
}
OrderAddress
Address format used in orders.
interface OrderAddress extends Omit<Address, 'id' | 'createdAt' | 'updatedAt'> {
countryCode?: Maybe<string>
}
Customer
Customer information with addresses.
interface Customer extends Node {
title?: Maybe<string>
firstName: string
lastName: string
phoneNumber?: Maybe<string>
emailAddress: string
addresses?: Maybe<Array<Address>>
}
CreateCustomerInput
Input type for creating a new customer.
type CreateCustomerInput = Omit<Customer, 'id' | 'createdAt' | 'updatedAt' | 'addresses'>
OrderLine
Order line item with pricing details.
interface OrderLine extends Node {
unitPrice: Price
unitPriceWithTax: Price
linePrice: Price
linePriceWithTax: Price
discountedUnitPrice: Price
discountedUnitPriceWithTax: Price
discountedLinePrice: Price
discountedLinePriceWithTax: Price
proratedUnitPrice: Price
proratedUnitPriceWithTax: Price
proratedLinePrice: Price
proratedLinePriceWithTax: Price
quantity: number
featuredAsset?: Maybe<Asset>
productVariant: ProductVariant
}
Payment
Payment information for an order.
interface Payment extends Node {
method: string
state: string
transactionId?: Maybe<string>
amount: Price
metadata?: Maybe<JSON>
}
PaymentMethodQuote
Available payment method with eligibility information.
interface PaymentMethodQuote extends Omit<Node, 'createdAt' | 'updatedAt'> {
code: string
name: string
description: string
isEligible: boolean
eligibilityMessage: string
}
ShippingMethodQuote
Available shipping method with pricing.
interface ShippingMethodQuote extends Omit<Node, 'createdAt' | 'updatedAt'> {
price: Price
priceWithTax: Price
code: string
name: string
description: string
metadata: JSON
}
OrderTaxSummary
Tax summary for an order.
interface OrderTaxSummary {
description: string
taxBase: number
taxRate: number
taxTotal: number
}
OrderPriceData
Price data for an order.
interface OrderPriceData {
subTotal: number
subTotalWithTax: number
total: number
totalWithTax: number
shipping: number
shippingWithTax: number
currencyCode: CurrencyCode
taxSummary: Array<OrderTaxSummary>
}
Promotion
Promotion or coupon information.
interface Promotion {
couponCode: string
description: string
enabled: boolean
name: string
perCustomerUsageLimit: number
}
Order
Complete order with all details.
interface Order extends Node, OrderPriceData {
code: string
active: boolean
state: string
totalQuantity: number
customer?: Maybe<Customer>
billingAddress?: Maybe<OrderAddress>
shippingAddress?: Maybe<OrderAddress>
lines: Array<OrderLine>
payments?: Maybe<Array<Payment>>
history: HistoryEntryList
discounts: Discount[]
promotions: Promotion[]
couponCodes: string[]
shippingLines: ShippingLine[]
orderPlacedAt: string
}
UpdateOrderInput
Input type for updating an order.
interface UpdateOrderInput {
billingAddress?: Maybe<CreateAddressInput>
shippingAddress?: Maybe<CreateAddressInput>
shippingMethodId?: Maybe<string>
paymentMethodCode?: Maybe<string>
customer?: Maybe<CreateCustomerInput>
customFields?: Record<string, unknown>
couponCode?: {
code: Maybe<string>
remove?: boolean
}
}
ShippingMethod
Shipping method information.
interface ShippingMethod {
id: string
name: string
}
ShippingLine
Shipping line item with pricing.
interface ShippingLine {
id: string
priceWithTax: Price
price: Price
shippingMethod: ShippingMethod
}
HistoryEntryList
Paginated list of history entries.
interface HistoryEntryList {
items: Array<HistoryEntry>
totalItems: number
}
Discount
Discount applied to an order.
interface Discount {
type: string
description: string
amount: Price
amountWithTax: Price
}
HistoryEntry
Order history entry tracking state changes.
interface HistoryEntry extends Node {
id: string
type: string
data: { from: string; to: string; [key: string]: string }
}
OrderFilterParameter
Filter parameters for querying orders.
interface OrderFilterParameter {
CustomerMessage?: Maybe<StringOperators>
active?: Maybe<BooleanOperators>
code?: Maybe<StringOperators>
createdAt?: Maybe<DateOperators>
currencyCode?: Maybe<StringOperators>
id?: Maybe<IdOperators>
newCustomer?: Maybe<BooleanOperators>
orderPlacedAt?: Maybe<DateOperators>
shipping?: Maybe<NumberOperators>
shippingWithTax?: Maybe<NumberOperators>
state?: Maybe<StringOperators>
subTotal?: Maybe<NumberOperators>
subTotalWithTax?: Maybe<NumberOperators>
total?: Maybe<NumberOperators>
totalQuantity?: Maybe<NumberOperators>
totalWithTax?: Maybe<NumberOperators>
type?: Maybe<StringOperators>
updatedAt?: Maybe<DateOperators>
}
OrderSortParameter
Sort parameters for ordering order lists.
interface OrderSortParameter {
CustomerMessage?: Maybe<SortOrder>
code?: Maybe<SortOrder>
createdAt?: Maybe<SortOrder>
id?: Maybe<SortOrder>
newCustomer?: Maybe<SortOrder>
orderPlacedAt?: Maybe<SortOrder>
shipping?: Maybe<SortOrder>
shippingWithTax?: Maybe<SortOrder>
state?: Maybe<SortOrder>
subTotal?: Maybe<SortOrder>
subTotalWithTax?: Maybe<SortOrder>
total?: Maybe<SortOrder>
totalQuantity?: Maybe<SortOrder>
totalWithTax?: Maybe<SortOrder>
updatedAt?: Maybe<SortOrder>
}
FacetFilterParameter
Filter parameters for querying facets.
interface FacetFilterParameter {
code?: Maybe<StringOperators>
createdAt?: Maybe<DateOperators>
id?: Maybe<IdOperators>
languageCode?: Maybe<StringOperators>
name?: Maybe<StringOperators>
updatedAt?: Maybe<DateOperators>
}
FacetSortParameter
Sort parameters for ordering facet lists.
interface FacetSortParameter {
code?: Maybe<SortOrder>
createdAt?: Maybe<SortOrder>
id?: Maybe<SortOrder>
name?: Maybe<SortOrder>
updatedAt?: Maybe<SortOrder>
}
FacetListOptions
Options for querying facet lists.
interface FacetListOptions {
filter?: Maybe<FacetFilterParameter>
filterOperator?: Maybe<LogicalOperator>
skip?: Maybe<number>
sort?: Maybe<FacetSortParameter>
take?: Maybe<number>
}
OrderListOptions
Options for querying order lists.
interface OrderListOptions {
filter?: Maybe<OrderFilterParameter>
filterOperator?: Maybe<LogicalOperator>
skip?: Maybe<number>
sort?: Maybe<OrderSortParameter>
take?: Maybe<number>
}
OrderList
Paginated list of orders.
interface OrderList extends PaginatedList {
items: Array<Order>
totalItems: number
}
CollectionSortParameter
Sort parameters for ordering collection lists.
interface CollectionSortParameter {
id?: Maybe<SortOrder>
createdAt?: Maybe<SortOrder>
updatedAt?: Maybe<SortOrder>
name?: Maybe<SortOrder>
slug?: Maybe<SortOrder>
position?: Maybe<SortOrder>
description?: Maybe<SortOrder>
parentId?: Maybe<SortOrder>
}
CollectionFilterParameter
Filter parameters for querying collections.
interface CollectionFilterParameter {
id?: Maybe<IdOperators>
createdAt?: Maybe<DateOperators>
updatedAt?: Maybe<DateOperators>
languageCode?: Maybe<StringOperators>
name?: Maybe<StringOperators>
slug?: Maybe<StringOperators>
position?: Maybe<NumberOperators>
description?: Maybe<StringOperators>
parentId?: Maybe<IdOperators>
_and?: Maybe<CollectionFilterParameter[]>
_or?: Maybe<CollectionFilterParameter[]>
}
CollectionListOptions
Options for querying collection lists.
interface CollectionListOptions {
topLevelOnly?: Maybe<boolean>
skip?: Maybe<number>
take?: Maybe<number>
sort?: Maybe<CollectionSortParameter>
filter?: Maybe<CollectionFilterParameter>
filterOperator?: Maybe<LogicalOperator>
}
Badge
Badge associated with a collection.
interface Badge {
id: string
createdAt: string
updatedAt: string
collection: Collection
collectionId: string
position: string
asset: Asset
assetId: string
}
CollectionSearchResponse
Collection with hierarchy slug for search results.
interface CollectionSearchResponse extends Collection {
hierarchySlug: string
}
UseSearchFieldResponse
Response structure from search field queries.
interface UseSearchFieldResponse {
collections?: CollectionSearchResponse[]
items: SearchResponse['items']
totalItems: number
facets: GroupedFacetValues
}
AddItemToOrderInput
Input for adding an item to an order.
interface AddItemToOrderInput {
productVariantId: string
quantity: number
}
AdjustOrderLineInput
Input for adjusting an order line quantity.
interface AdjustOrderLineInput {
orderLineId: string
quantity: number
}
LoginInput
Input for user login.
interface LoginInput {
username: string
password: string
rememberMe?: boolean
}
RequestPasswordResetInput
Input for requesting a password reset.
interface RequestPasswordResetInput {
email: string
}
ResetPasswordInput
Input for resetting a password with token.
interface ResetPasswordInput {
token: string
password: string
}
AsChildProps
Props supporting the "asChild" pattern for flexible component composition.
interface AsChildProps<Children = ReactNode> {
asChild?: boolean
className?: string
style?: CSSProperties
children?: Children
}
PersistOptions
Options for data persistence.
interface PersistOptions {
enabled: boolean
storage?: Storage
maxAge?: number
}
IGraphQLSDK
Interface for GraphQL SDK operations.
interface IGraphQLSDK {
setUpdates(updates: BuilderQueryUpdates): void
getQueries(): BuilderQueries
createRequest<T = unknown, Vars extends Record<string, unknown> = Record<string, unknown>>(
json: BuilderQueryWithInheritFieldsFrom<Vars>,
variables: ExpectedVariables<Vars>,
mutation?: boolean,
): Promise<AxiosResponse<T>>
createGraphQLQuery(
json: BuilderQuery,
variables?: Record<string, unknown>,
): {
query: string
variables: unknown
operationName: string
}
createGraphQLMutation(
json: BuilderQuery,
variables?: Record<string, unknown>,
): {
query: string
variables: unknown
operationName: string
}
updateFields(source: BuilderQueries, updates: BuilderQueryUpdates): BuilderQueries
replaceChildObjectVariables(json: unknown, variables?: Record<string, unknown>): void
}
BuilderQueryWithInheritFieldsFrom lets a request inherit fields from an existing registered query key:
type BuilderQueryWithInheritFieldsFrom<
Vars extends Record<string, unknown> = Record<string, unknown>,
> = Omit<BuilderQuery<Vars>, 'fields'> &
RequireAtLeastOne<{ fields: Field[]; inheritFieldsFrom: string }>
This means a request can:
- provide only
fields - provide only
inheritFieldsFrom - provide both, in which case
fieldsare merged into the inherited field selection
Enums
SortOrder
Sort order direction.
enum SortOrder {
Asc = 'ASC',
Desc = 'DESC',
}
CurrencyCode
ISO currency codes for all supported currencies.
enum CurrencyCode {
/** United Arab Emirates dirham */
Aed = 'AED',
/** Afghan afghani */
Afn = 'AFN',
// ... (200+ currency codes)
/** United States dollar */
Usd = 'USD',
// ... (remaining currency codes)
}
LanguageCode
ISO language codes for all supported languages.
enum LanguageCode {
/** Afrikaans */
Af = 'af',
/** English */
En = 'en',
/** Spanish */
Es = 'es',
// ... (300+ language codes)
}
AssetType
Types of media assets.
enum AssetType {
Binary = 'BINARY',
Image = 'IMAGE',
Video = 'VIDEO',
}
LogicalOperator
Logical operators for combining filters.
enum LogicalOperator {
And = 'AND',
Or = 'OR',
}
ErrorCode
Error codes for various e-commerce operation failures.
enum ErrorCode {
AlreadyLoggedInError = 'ALREADY_LOGGED_IN_ERROR',
CouponCodeExpiredError = 'COUPON_CODE_EXPIRED_ERROR',
CouponCodeInvalidError = 'COUPON_CODE_INVALID_ERROR',
CouponCodeLimitError = 'COUPON_CODE_LIMIT_ERROR',
EmailAddressConflictError = 'EMAIL_ADDRESS_CONFLICT_ERROR',
GuestCheckoutError = 'GUEST_CHECKOUT_ERROR',
IdentifierChangeTokenExpiredError = 'IDENTIFIER_CHANGE_TOKEN_EXPIRED_ERROR',
IdentifierChangeTokenInvalidError = 'IDENTIFIER_CHANGE_TOKEN_INVALID_ERROR',
IneligiblePaymentMethodError = 'INELIGIBLE_PAYMENT_METHOD_ERROR',
IneligibleShippingMethodError = 'INELIGIBLE_SHIPPING_METHOD_ERROR',
InsufficientStockError = 'INSUFFICIENT_STOCK_ERROR',
InvalidCredentialsError = 'INVALID_CREDENTIALS_ERROR',
MissingPasswordError = 'MISSING_PASSWORD_ERROR',
NativeAuthStrategyError = 'NATIVE_AUTH_STRATEGY_ERROR',
NegativeQuantityError = 'NEGATIVE_QUANTITY_ERROR',
NotVerifiedError = 'NOT_VERIFIED_ERROR',
NoActiveOrderError = 'NO_ACTIVE_ORDER_ERROR',
OrderLimitError = 'ORDER_LIMIT_ERROR',
OrderModificationError = 'ORDER_MODIFICATION_ERROR',
OrderPaymentStateError = 'ORDER_PAYMENT_STATE_ERROR',
OrderStateTransitionError = 'ORDER_STATE_TRANSITION_ERROR',
PasswordAlreadySetError = 'PASSWORD_ALREADY_SET_ERROR',
PasswordResetTokenExpiredError = 'PASSWORD_RESET_TOKEN_EXPIRED_ERROR',
PasswordResetTokenInvalidError = 'PASSWORD_RESET_TOKEN_INVALID_ERROR',
PasswordValidationError = 'PASSWORD_VALIDATION_ERROR',
PaymentDeclinedError = 'PAYMENT_DECLINED_ERROR',
PaymentFailedError = 'PAYMENT_FAILED_ERROR',
UnknownError = 'UNKNOWN_ERROR',
VerificationTokenExpiredError = 'VERIFICATION_TOKEN_EXPIRED_ERROR',
VerificationTokenInvalidError = 'VERIFICATION_TOKEN_INVALID_ERROR',
}
QueryKeys
Query cache keys for React Query.
enum QueryKeys {
ACTIVE_ORDER = 'activeOrder',
ACTIVE_CHANNEL = 'activeChannel',
ACTIVE_CUSTOMER = 'activeCustomer',
ACTIVE_CUSTOMER_ORDERS = 'activeCustomerOrders',
AVAILABLE_COUNTRIES = 'availableCountries',
FACETS = 'facets',
ORDER_BY_CODE = 'orderByCode',
ORDER_STATES = 'orderStates',
PRODUCT = 'product',
PAYMENT_METHODS = 'paymentMethods',
SEARCH = 'search',
SEARCH_FIELD = 'searchField',
SHIPPING_METHODS = 'shippingMethods',
}
Basic Usage
Using Error Types
- React
- React Native
import { ErrorResult, ErrorCode } from '@haus-storefront-react/shared-types'
function handleError(): ErrorResult {
return {
errorCode: ErrorCode.InvalidCredentialsError,
message: 'Invalid username or password',
code: 'AUTH_001',
}
}
import { ErrorResult, ErrorCode } from '@haus-storefront-react/shared-types'
function handleError(): ErrorResult {
return {
errorCode: ErrorCode.InvalidCredentialsError,
message: 'Invalid username or password',
code: 'AUTH_001',
}
}
Using Utility Types
- React
- React Native
import { Maybe, WithRequired } from '@haus-storefront-react/shared-types'
// Maybe type for nullable values
type UserName = Maybe<string> // string | null
// WithRequired makes specific keys required
interface User {
id?: string
name: string
email?: string
}
type UserWithId = WithRequired<User, 'id'> // id is now required
import { Maybe, WithRequired } from '@haus-storefront-react/shared-types'
// Maybe type for nullable values
type UserName = Maybe<string> // string | null
// WithRequired makes specific keys required
interface User {
id?: string
name: string
email?: string
}
type UserWithId = WithRequired<User, 'id'> // id is now required
Using E-commerce Types
- React
- React Native
import {
Product,
CurrencyCode,
LanguageCode,
} from '@haus-storefront-react/shared-types'
const product: Product = {
id: '1',
name: 'Sample Product',
slug: 'sample-product',
description: 'A sample product',
languageCode: LanguageCode.En,
currencyCode: CurrencyCode.Usd,
assets: [],
collections: [],
facetValues: [],
featuredAsset: null,
optionGroups: [],
variantList: {
items: [],
totalItems: 0,
},
variants: [],
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
}
import {
Product,
CurrencyCode,
LanguageCode,
} from '@haus-storefront-react/shared-types'
const product: Product = {
id: '1',
name: 'Sample Product',
slug: 'sample-product',
description: 'A sample product',
languageCode: LanguageCode.En,
currencyCode: CurrencyCode.Usd,
assets: [],
collections: [],
facetValues: [],
featuredAsset: null,
optionGroups: [],
variantList: {
items: [],
totalItems: 0,
},
variants: [],
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T00:00:00Z',
}
Advanced Usage
GraphQL Query Building
- React
- React Native
import {
BuilderQuery,
BuilderQueryUpdates,
Field,
NestedField,
FragmentField,
} from '@haus-storefront-react/shared-types'
// Basic query structure
const query: BuilderQuery<{ id: string }> = {
operation: 'getProduct',
fields: [
'id',
'name',
'description',
{
variants: ['id', 'name', 'price', 'priceWithTax'],
},
],
variables: { id: '1' },
}
// Nested field structure
const nestedFields: NestedField = {
product: [
'id',
'name',
{
variants: ['id', 'name', 'price'],
},
],
}
// Fragment field
const fragmentField: FragmentField = {
operation: 'ProductFragment',
fields: ['id', 'name', 'description'],
fragment: true,
}
// Query updates for plugins
const queryUpdates: BuilderQueryUpdates = {
products: {
fields: ['id', 'name', 'customField'],
},
collections: {
fields: ['id', 'name', 'description', 'customField'],
},
}
import {
BuilderQuery,
BuilderQueryUpdates,
Field,
NestedField,
FragmentField,
} from '@haus-storefront-react/shared-types'
// Basic query structure
const query: BuilderQuery<{ id: string }> = {
operation: 'getProduct',
fields: [
'id',
'name',
'description',
{
variants: ['id', 'name', 'price', 'priceWithTax'],
},
],
variables: { id: '1' },
}
// Nested field structure
const nestedFields: NestedField = {
product: [
'id',
'name',
{
variants: ['id', 'name', 'price'],
},
],
}
// Fragment field
const fragmentField: FragmentField = {
operation: 'ProductFragment',
fields: ['id', 'name', 'description'],
fragment: true,
}
// Query updates for plugins
const queryUpdates: BuilderQueryUpdates = {
products: {
fields: ['id', 'name', 'customField'],
},
collections: {
fields: ['id', 'name', 'description', 'customField'],
},
}
Plugin Configuration
- React
- React Native
import {
IVendurePluginConfig,
PluginFeatures,
ProviderDataMap,
BuilderQueryUpdates,
} from '@haus-storefront-react/shared-types'
// Plugin configuration interface
interface MyPluginFeatures {
feature1: boolean
feature2: boolean
}
interface MyPluginRequests {
getData: () => Promise<any>
updateData: (data: any) => Promise<void>
}
interface MyPluginSettings {
apiUrl: string
timeout: number
}
const pluginConfig: IVendurePluginConfig<
MyPluginFeatures,
MyPluginRequests,
MyPluginSettings
> = {
name: 'my-plugin',
enabled: true,
enableFeatures: {
feature1: true,
feature2: false,
},
queryUpdates: {
products: {
fields: ['id', 'name', 'customField'],
},
},
requests: {
getData: async () => ({ data: 'test' }),
updateData: async (data) => console.log('Updated:', data),
},
providers: [],
settings: {
apiUrl: 'https://api.example.com',
timeout: 5000,
},
setSdk: (sdk) => {},
setProviders: (providers) => {},
setEnabled: (enabled) => {},
setEnableFeatures: (features) => {},
setQueryUpdates: (updates) => {},
setRequests: (requests) => {},
setSettings: (settings) => {},
getSdk: () => ({} as any),
getProviders: () => [],
getEnabled: () => true,
getEnabledFeatures: () => ({}),
getQueryUpdates: () => ({}),
getRequests: () => ({} as any),
getSettings: () => ({} as any),
}
import {
IVendurePluginConfig,
PluginFeatures,
ProviderDataMap,
BuilderQueryUpdates,
} from '@haus-storefront-react/shared-types'
interface MyPluginFeatures {
feature1: boolean
feature2: boolean
}
interface MyPluginRequests {
getData: () => Promise<any>
updateData: (data: any) => Promise<void>
}
interface MyPluginSettings {
apiUrl: string
timeout: number
}
const pluginConfig: IVendurePluginConfig<
MyPluginFeatures,
MyPluginRequests,
MyPluginSettings
> = {
name: 'my-plugin',
enabled: true,
enableFeatures: {
feature1: true,
feature2: false,
},
queryUpdates: {
products: {
fields: ['id', 'name', 'customField'],
},
},
requests: {
getData: async () => ({ data: 'test' }),
updateData: async (data) => console.log('Updated:', data),
},
providers: [],
settings: {
apiUrl: 'https://api.example.com',
timeout: 5000,
},
setSdk: (sdk) => {},
setProviders: (providers) => {},
setEnabled: (enabled) => {},
setEnableFeatures: (features) => {},
setQueryUpdates: (updates) => {},
setRequests: (requests) => {},
setSettings: (settings) => {},
getSdk: () => ({} as any),
getProviders: () => [],
getEnabled: () => true,
getEnabledFeatures: () => ({}),
getQueryUpdates: () => ({}),
getRequests: () => ({} as any),
getSettings: () => ({} as any),
}
Conditional Type Usage
- React
- React Native
import {
Product,
ProductVariant,
Price,
Maybe,
ArrayElement,
} from '@haus-storefront-react/shared-types'
function formatProductPrices(product: Product): string[] {
// Extract element type from array
type Variant = ArrayElement<Product['variants']>
return product.variants.map((variant: Variant) => {
// Handle Maybe types
const price: Maybe<Price> = variant.price
if (!price) return 'Price unavailable'
if (typeof price === 'number') {
return `$${price.toFixed(2)}`
}
if ('value' in price) {
return `$${price.value.toFixed(2)}`
}
return `$${price.min.toFixed(2)} - $${price.max.toFixed(2)}`
})
}
import {
Product,
ProductVariant,
Price,
Maybe,
ArrayElement,
} from '@haus-storefront-react/shared-types'
function formatProductPrices(product: Product): string[] {
type Variant = ArrayElement<Product['variants']>
return product.variants.map((variant: Variant) => {
const price: Maybe<Price> = variant.price
if (!price) return 'Price unavailable'
if (typeof price === 'number') {
return `$${price.toFixed(2)}`
}
if ('value' in price) {
return `$${price.value.toFixed(2)}`
}
return `$${price.min.toFixed(2)} - $${price.max.toFixed(2)}`
})
}
Made with ❤️ by Haus Tech Team