// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { ModelTypes } from '../../client'; import { BaseClient, ClientInternalsGetter, ModelIntrospectionSchema, ServerClientGenerationParams, } from '../../bridge-types'; import { ModelOperation } from '../APIClient'; import { listFactory } from '../operations/list'; import { indexQueryFactory } from '../operations/indexQuery'; import { getFactory } from '../operations/get'; import { getSecondaryIndexesFromSchemaModel, excludeDisabledOps, } from '../clientUtils'; export function generateModelsProperty = never>( client: BaseClient, params: ServerClientGenerationParams, getInternals: ClientInternalsGetter, ): ModelTypes | ModelTypes { const models = {} as any; const { config } = params; const useContext = params.amplify === null; if (!config) { throw new Error('generateModelsProperty cannot retrieve Amplify config'); } if (!config.API?.GraphQL) { return {} as ModelTypes; } const modelIntrospection: ModelIntrospectionSchema | undefined = config.API.GraphQL.modelIntrospection; if (!modelIntrospection) { return {} as ModelTypes; } const SSR_UNSUPORTED_OPS = [ 'ONCREATE', 'ONUPDATE', 'ONDELETE', 'OBSERVEQUERY', ]; for (const model of Object.values(modelIntrospection.models)) { const { name } = model; models[name] = {} as Record; const enabledModelOps = excludeDisabledOps(modelIntrospection, name); Object.entries(enabledModelOps).forEach(([key, { operationPrefix }]) => { const operation = key as ModelOperation; // subscriptions are not supported in SSR if (SSR_UNSUPORTED_OPS.includes(operation)) return; if (operation === 'LIST') { models[name][operationPrefix] = listFactory( client, modelIntrospection, model, getInternals, useContext, ); } else { models[name][operationPrefix] = getFactory( client, modelIntrospection, model, operation, getInternals, useContext, ); } }); const secondaryIdxs = getSecondaryIndexesFromSchemaModel(model); for (const idx of secondaryIdxs) { models[name][idx.queryField] = indexQueryFactory( client, modelIntrospection, model, idx, getInternals, useContext, ); } } return models; }