import fs from 'fs';
import path from 'path';
export function generateTypedGraphQLHook(
rootPath: string,
opName: string,
type: 'query' | 'mutation',
variablesType?: string,
responseType?: string,
) {
const hooksDir = path.join(rootPath, 'hooks');
if (!fs.existsSync(hooksDir)) fs.mkdirSync(hooksDir);
const hookName = 'use' + opName;
let code = '';
if (type === 'query') {
code = `
import { useQuery } from "@apollo/client";
import { ${opName} } from "../graphql/${opName}.graphql";
import type { ${responseType}, ${variablesType} } from "../graphql/generated";
export function ${hookName}(variables: ${variablesType}) {
return useQuery<${responseType}, ${variablesType}>(${opName}, { variables });
}
`;
} else {
code = `
import { useMutation } from "@apollo/client";
import { ${opName} } from "../graphql/${opName}.graphql";
import type { ${responseType}, ${variablesType} } from "../graphql/generated";
export function ${hookName}() {
return useMutation<${responseType}, ${variablesType}>(${opName});
}
`;
}
const filePath = path.join(hooksDir, `${hookName}.ts`);
fs.writeFileSync(filePath, code);
return filePath;
}
//generateTypedGraphQLHook(ROOT, "GetUser", "query", "GetUserQueryVariables", "GetUserQuery");
//generateTypedGraphQLHook(ROOT, "UpdateUser", "mutation", "UpdateUserMutationVariables", "UpdateUserMutation");
// Example usage:
// const hookPath = generateTypedGraphQLHook(ROOT, "GetUser", "query", "GetUserQueryVariables", "GetUserQuery");
// console.log(`Generated hook at: ${hookPath}`);
// const hookPath2 = generateTypedGraphQLHook(ROOT, "UpdateUser", "mutation", "UpdateUserMutationVariables", "UpdateUserMutation");
// console.log(`Generated hook at: ${hookPath2}`);
// This will create files like hooks/useGetUser.ts and hooks/useUpdateUser.ts
// with the appropriate typed hooks for Apollo Client.
// Make sure to adjust import paths based on your project structure.
// Also ensure that the GraphQL operations and generated types exist.
// You can call this function from your code generation script after generating the GraphQL operations and types.
// This will help you maintain type safety and consistency across your React components using Apollo Client.
// Note: This code assumes you have a GraphQL setup with Apollo Client and TypeScript.
// Adjust the import paths and type names as per your actual GraphQL schema and generated types.
// You can integrate this function into your existing code generation workflow.
// Remember to install necessary dependencies if you haven't already:
// npm install @apollo/client graphql
// or
// yarn add @apollo/client graphql
// This will ensure you have Apollo Client set up in your project.
// Also, ensure that your TypeScript configuration allows for proper module resolution.
// You might need to adjust tsconfig.json settings like "baseUrl" and "paths" for better import management.
// Finally, test the generated hooks in your React components to ensure they work as expected.
// Example React component usage:
/*
import React from "react";
import { useGetUser } from "../hooks/useGetUser";
import { useUpdateUser } from "../hooks/useUpdateUser";
import type { GetUserQueryVariables } from "../graphql/generated";
import type { UpdateUserMutationVariables } from "../graphql/generated";
const UserComponent: React.FC = () => {
const { data, loading, error } = useGetUser({ id: "1" } as GetUserQueryVariables);
const [updateUser] = useUpdateUser();
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
const handleUpdate = () => {
updateUser({ variables: { id: "1", name: "New Name" } as UpdateUserMutationVariables });
};
return (
<div>
<h1>{data?.user.name}</h1>
<button onClick={handleUpdate}>Update User</button>
</div>
);
};
export default UserComponent;
*/
// This example demonstrates how to use the generated hooks in a React component.
// Adjust the component logic as per your requirements.
// Remember to handle loading and error states appropriately in your components.
// This will help you build a robust and type-safe React application with Apollo Client and GraphQL.
// You can further enhance this function to include additional options or configurations as needed.
// Happy coding!