I'm implementing a typescript project with aws-amplify in a monorepo. The monorepo has a web project under: packages/web
and models project which includes graphql operations and types under: packages/models
. After creating my graphql schema in amplify, I am generating the operations and types with the help of amplify codegen
to packages/models/src/graphql/
So far so good, in the Vue project I can import the operations and types as
import {listOrganizations, ListOrganizationsQuery} from "models";
, executed the queries, get the result. When it is time to use an action in a component, I do import types from models again and use.
The idea I come up is if there is a way to import the types from the models project, and include all the types in the web project in a .d.ts
file to skip importing types from the models repo. So each time I generate the graphql operations and types, I want web repo to import types and declare globally in web project to be able to skip importing types.
What I have tried:
Create a api.d.ts
file in packages/web/src
Import types from packages/models/src/graphql/API.ts
What I am trying to do here is import and declare all the types from models globally, but I am stuck at this point.
packages/models/models/src/graphql/API.ts
export type ListOrganizationsQuery = {
listOrganizations: {
__typename: "ModelOrganizationConnection",
items: Array< {
__typename: "Organization",
id: string,
name: string,
externalId: string | null,
status: OrganizationStatus,
logo: string,
} | null > | null,
nextToken: string | null,
} | null,
};
packages/web/src/api.d.ts
import "models/src/graphql/API.ts";
VSCode is does not recognise the imported types and the compiler does not compile as long as my way of doing this probably not right. Is there any way to import all the types and declare globally? Or is there any other best practice that I should apply instead of doing this way I have tried?
After trying different workarounds a couple of days I finally have acknowledged what I was trying to do. The purpose of importing and declaring types globally was that amplify codegen
was creating the types for the queries, mutations and subscriptions but was not creating types for the models. So I had to re-write models in the frontend application but each time I update the graphql schema, I needed to update frontend types as well.
My workaround for this, to dynamically import query types from the packages/models into declarations.d.ts
which is in my frontend project. And just declare similar model types there.
Example
packages/models/src/graphql/API.ts
export type GetOrganizationQuery = {
getOrganization: {
__typename: "Organization",
id: string,
name: string,
decription: string | null,
...
};
packages/web/src/types/declarations.d.ts
declare type TOrganization = import("../path/to/models").GetOrganizationQuery["getOrganization"];