### Install Apollo Client and GraphQL dependencies
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
This command uses npm to install the necessary packages: `@apollo/client` for the GraphQL client and `graphql` for GraphQL parsing and utilities. These are fundamental for any Apollo Client setup.
```Shell
npm i @apollo/client graphql
```
--------------------------------
### Complete index.tsx for Apollo Client Integration
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
Provides the full `index.tsx` file demonstrating the complete setup of a React application with Apollo Client. This includes importing necessary modules, initializing `ApolloClient` with a GraphQL URI and `InMemoryCache`, and rendering the application wrapped within `ApolloProvider`.
```TypeScript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://s5.sanctuaryhealth.io/graphql',
cache: new InMemoryCache(),
});
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```
--------------------------------
### Javascript Fetch Example for GraphQL API Communication
Source: https://docs.sanctuaryhealth.io/docs/s5/tutorial/gettingStarted
This Javascript snippet demonstrates how to send a GraphQL query to the Sanctuary Health API using the `fetch` API. It constructs a POST request with `application/json` content type, includes an API key for authentication, and embeds a GraphQL query and variables in the request body to retrieve post details by ID.
```Javascript
fetch("https://s5.sanctuaryhealth.io/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: "9677bbd3-4b5b-4a2f-a085-201771d6ad9c"
},
body: JSON.stringify({
"query": "query gettingStarted($where: PostDetailsWhere) {\n getPostDetails(where: $where) {\n id\n title\n }\n }",
"variables": {
"where": {
"id": {
"_eq": "64437043-d962-4402-9389-7ca4ade821b4"
}
}
}
})
})
.then((response) => response.json())
.then((data) => console.log(data))
```
--------------------------------
### Perform GraphQL Query with Javascript Fetch
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/gettingStarted
This Javascript example demonstrates how to make a POST request to a GraphQL endpoint using the `fetch` API. It includes setting `Content-Type` and `apikey` headers, constructing a GraphQL query with variables in the request body, and processing the JSON response. This snippet can be run directly in a browser console.
```Javascript
fetch("https://v4-0-dot-livitay.appspot.com/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: "9677bbd3-4b5b-4a2f-a085-201771d6ad9c"
},
body: JSON.stringify({
query: `query gettingStarted($sequelizeQuery: SequelizeQuery) {
getPosts(sequelizeQuery: $sequelizeQuery) {
id
title
}
}`,
variables: {
sequelizeQuery: {
where: '{ "id": "c4cf717d-a638-49d8-bbcd-fafd2142d284" }'
}
}
})
})
.then((response) => response.json())
.then((data) => console.log(data))
```
--------------------------------
### Complete Apollo Client setup in `index.tsx`
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/advancedApolloNetworking
This comprehensive example illustrates the full setup of an Apollo Client application within an `index.tsx` file. It includes all necessary React and Apollo Client imports, defines an `HttpLink` and an `ApolloLink` for authentication, instantiates the client with concatenated links, and renders the React application wrapped with `ApolloProvider`.
```typescript
import React from 'react';
import ReactDOM from 'react/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { ApolloClient, ApolloLink, ApolloProvider, InMemoryCache, HttpLink, concat } from '@apollo/client';
const httpLink = new HttpLink({ uri: 'https://s5.sanctuaryhealth.io/graphql' })
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
apikey: "9677bbd3-4b5b-4a2f-a085-201771d6ad9c"
}
}));
return forward(operation);
})
const client = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, httpLink),
});
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```
--------------------------------
### GraphQL Query Body with Variables for Post Details
Source: https://docs.sanctuaryhealth.io/docs/s5/tutorial/gettingStarted
This example shows the structure of the HTTP POST request body for a GraphQL query. It includes a "query" string for "getPostDetails" and a "variables" object to filter by a specific post ID. The entire body is stringified JSON, suitable for a JavaScript context.
```JavaScript
body: JSON.stringify({
"query": "query gettingStarted($where: PostDetailsWhere) {\n getPostDetails(where: $where) {\n id\n title\n }\n }",
"variables": {
"where": {
"id": {
"_eq": "64437043-d962-4402-9389-7ca4ade821b4"
}
}
}
})
```
--------------------------------
### Initialize React Project with TypeScript
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/projectSetup
This command initializes a new React project named 'react-example' using the `create-react-app` toolchain with the TypeScript template. The second command navigates into the newly created project directory.
```Shell
npx create-react-app react-example --template typescript
cd react-example
```
--------------------------------
### Start React Development Server
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/generatingAndUsingQueries
Initiate the development server for the React project, which automatically opens the application in a browser for live development.
```bash
npm start
```
--------------------------------
### Example URL for Image Optimization with h, w, and q
Source: https://docs.sanctuaryhealth.io/docs/s5/images
Demonstrates how to use height, width, and quality parameters in an image URL to optimize size and compression, reducing a 2.4MB image to 2.3KB.
```URL
https://media.sanctuaryhealth.io/00000000-0000-0000-0000-000000000001/f859c2b9-e3b6-4961-9acb-503381d34f5b?h=100&w=100&q=50
```
--------------------------------
### Start React Development Server
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/generatingAndUsingQueries
Command to start the local development server for a React application, typically opening the project in a browser.
```Shell
npm start
```
--------------------------------
### Initialize React Project with TypeScript
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/projectSetup
This command uses `npx` to execute `create-react-app`, initializing a new React project named 'react-example' with the TypeScript template. After creation, it changes the current directory into the newly created project folder.
```Shell
npx create-react-app react-example --template typescript
cd react-example
```
--------------------------------
### HTTP Request Headers for Sanctuary Health API Authentication
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/gettingStarted
Demonstrates the essential HTTP headers required for authenticating requests to the Sanctuary Health API. It specifies the 'Content-Type' as 'application/json' and includes the 'apikey' header with a placeholder API key for authorization.
```JSON
headers: {
"Content-Type": "application/json",
"apikey": "9677bbd3-4b5b-4a2f-a085-201771d6ad9c"
}
```
--------------------------------
### Complete Apollo Client Setup in React Application (index.tsx)
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/advancedApolloNetworking
This comprehensive example illustrates the full setup of an Apollo Client in a React application's `index.tsx` file. It defines an `HttpLink`, an `ApolloLink` for authentication middleware, concatenates them, and provides the client via `ApolloProvider`.
```typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { ApolloClient, ApolloLink, ApolloProvider, InMemoryCache, HttpLink, concat } from '@apollo/client';
const httpLink = new HttpLink({ uri: 'https://v4-0-dot-livitay.appspot.com/graphql' })
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
apikey: "9677bbd3-4b5b-4a2f-a085-201771d6ad9c"
}
}));
return forward(operation);
})
const client = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, httpLink),
});
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```
--------------------------------
### HTTP Request Headers for API Key Authentication
Source: https://docs.sanctuaryhealth.io/docs/s5/tutorial/gettingStarted
This snippet demonstrates how to include the API key in the HTTP request headers. The "apikey" header is crucial for authentication and content filtering. The "Content-Type" header is set to "application/json" for proper request parsing.
```JSON
headers: {
"Content-Type": "application/json",
"apikey": "9677bbd3-4b5b-4a2f-a085-201771d6ad9c"
}
```
--------------------------------
### Initial React application entry point (index.tsx)
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
This code block represents the default structure of a React application's entry point, typically `src/index.tsx`. It sets up the root component for rendering the application into the DOM.
```TypeScript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```
--------------------------------
### Import Apollo Client modules
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
This line imports the core `ApolloClient` class and `InMemoryCache` from the `@apollo/client` package. `ApolloClient` is used to create the GraphQL client instance, while `InMemoryCache` handles caching GraphQL query results.
```TypeScript
import { ApolloClient, InMemoryCache } from '@apollo/client';
```
--------------------------------
### Import Apollo Client Core Components
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
Imports essential components `ApolloClient`, `InMemoryCache`, and `ApolloProvider` from the `@apollo/client` library, necessary for setting up Apollo Client in a React application.
```TypeScript
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
```
--------------------------------
### Install Apollo Client and GraphQL npm packages
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This command installs the @apollo/client and graphql npm packages. These are essential dependencies for setting up a GraphQL client in your project, enabling communication with GraphQL APIs.
```bash
npm i @apollo/client graphql
```
--------------------------------
### Complete Apollo Client Setup in React index.tsx
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This comprehensive snippet provides the full index.tsx file, showcasing the complete integration of Apollo Client into a React application. It includes React and ReactDOM imports, CSS, the main App component, Apollo Client initialization with a GraphQL URI and InMemoryCache, and the final rendering of the application wrapped within ApolloProvider for global state management.
```TypeScript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://v4-0-dot-livitay.appspot.com/graphql',
cache: new InMemoryCache(),
});
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```
--------------------------------
### Initialize Apollo Client with GraphQL endpoint
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
This snippet demonstrates how to instantiate `ApolloClient`. It configures the client with the GraphQL API URI and an `InMemoryCache` for efficient data management. This client instance will be used throughout the application to send GraphQL queries and mutations.
```TypeScript
const client = new ApolloClient({
uri: 'https://s5.sanctuaryhealth.io/graphql',
cache: new InMemoryCache(),
});
```
--------------------------------
### Install GraphQL Code Generator CLI and Plugins
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/installingGraphQLCodeGenerator
Installs the core GraphQL Code Generator CLI and specific plugins for TypeScript, GraphQL operations, and React Apollo. These packages are added as development dependencies using npm.
```Shell
npm i -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
```
--------------------------------
### Wrap React App Component with ApolloProvider
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/setupApolloClient
Illustrates how to wrap the main `` component with the `ApolloProvider` component, passing the initialized Apollo `client` instance as a prop. This makes the Apollo Client available to all child components within the React tree.
```TSX
```
--------------------------------
### Complete App.tsx File Example
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/generatingAndUsingQueries
The full `App.tsx` file demonstrating the integration of the `useGetPostsOperationQuery` hook. It imports the hook, calls it within the `App` component, and displays the returned data as a JSON string.
```tsx
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { useGetPostsOperationQuery } from './gql';
function App() {
const {data, loading, error} = useGetPostsOperationQuery({variables: {sequelizeQuery: {}}})
return (
);
}
export default App;
```
--------------------------------
### Install GraphQL Code Generator Development Dependencies
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/installingGraphQLCodeGenerator
This command installs the necessary development dependencies for GraphQL Code Generator using npm. It includes the core CLI package along with specific plugins for TypeScript, TypeScript operations, and React Apollo, which are essential for generating type-safe code based on your GraphQL schema.
```bash
npm i -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
```
--------------------------------
### package.json with 'gen' script for GraphQL Code Generator
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/installingGraphQLCodeGenerator
This JSON snippet illustrates the `package.json` file after the addition of a new 'gen' command within the 'scripts' section. The `"gen": "graphql-codegen -c codegen.ts"` entry enables running the GraphQL Code Generator via `npm run gen`, automating code generation based on the `codegen.ts` configuration.
```json
{
"name": "react-example",
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.7.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.11",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"graphql": "^16.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"gen": "graphql-codegen -c codegen.ts"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@graphql-codegen/cli": "^2.16.3",
"@graphql-codegen/typescript": "^2.8.7",
"@graphql-codegen/typescript-operations": "^2.5.12",
"@graphql-codegen/typescript-react-apollo": "^3.3.7"
}
}
```
--------------------------------
### package.json with 'gen' script for GraphQL Codegen
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/installingGraphQLCodeGenerator
This updated 'package.json' snippet shows the inclusion of a new 'gen' script within the 'scripts' section. This script executes 'graphql-codegen -c codegen.ts', enabling the automated generation of code based on GraphQL definitions by running 'npm run gen'.
```json
{
"name": "react-example",
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.7.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.11",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"graphql": "^16.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"gen": "graphql-codegen -c codegen.ts"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@graphql-codegen/cli": "^2.16.3",
"@graphql-codegen/typescript": "^2.8.7",
"@graphql-codegen/typescript-operations": "^2.5.12",
"@graphql-codegen/typescript-react-apollo": "^3.3.7"
}
}
```
--------------------------------
### Initial package.json for React GraphQL project
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/installingGraphQLCodeGenerator
This JSON snippet displays the initial `package.json` file for a React application, detailing its dependencies for Apollo Client, React, and TypeScript, along with development dependencies for GraphQL Code Generator. It represents the project's state before adding a custom code generation script.
```json
{
"name": "react-example",
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.7.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.11",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"graphql": "^16.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@graphql-codegen/cli": "^2.16.3",
"@graphql-codegen/typescript": "^2.8.7",
"@graphql-codegen/typescript-operations": "^2.5.12",
"@graphql-codegen/typescript-react-apollo": "^3.3.7"
}
}
```
--------------------------------
### Initial package.json for React GraphQL project
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/installingGraphQLCodeGenerator
This JSON snippet displays the 'package.json' file for a React application, outlining its core dependencies such as React, Apollo Client, and TypeScript, along with development dependencies for GraphQL Codegen. It represents the project's state before custom script additions.
```json
{
"name": "react-example",
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.7.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.11",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"graphql": "^16.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@graphql-codegen/cli": "^2.16.3",
"@graphql-codegen/typescript": "^2.8.7",
"@graphql-codegen/typescript-operations": "^2.5.12",
"@graphql-codegen/typescript-react-apollo": "^3.3.7"
}
}
```
--------------------------------
### Import ApolloClient and InMemoryCache from `@apollo/client`
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This line imports the core components ApolloClient and InMemoryCache from the @apollo/client library. ApolloClient manages GraphQL operations, while InMemoryCache handles local data caching for improved performance.
```typescript
import { ApolloClient, InMemoryCache } from '@apollo/client';
```
--------------------------------
### Wrap React App with ApolloProvider
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This snippet illustrates how to wrap your main component with the ApolloProvider. By passing the client instance as a prop, all child components within the tree gain access to the Apollo Client's state and functionalities.
```JSX
```
--------------------------------
### GraphQL Query and Variables in HTTP Request Body
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/gettingStarted
Illustrates the JSON structure for the HTTP POST request body when sending a GraphQL query to the Sanctuary Health API. It includes a GraphQL query string to fetch posts and a 'variables' object for filtering results using a Sequelize-like 'where' clause.
```JSON
body: JSON.stringify({
"query": "query gettingStarted($sequelizeQuery: SequelizeQuery) {\n getPosts(sequelizeQuery: $sequelizeQuery) {\n id\n title\n }\n }",
"variables": {
"sequelizeQuery": {
"where": "{ \"id\": \"c4cf717d-a638-49d8-bbcd-fafd2142d284\" }"
}
}
})
```
--------------------------------
### Import Apollo Client Components for React
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This snippet demonstrates the necessary imports from the @apollo/client library. It includes ApolloClient for client instance creation, InMemoryCache for caching, and ApolloProvider to make the client available throughout the React component tree.
```TypeScript
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
```
--------------------------------
### Define a GraphQL Fragment
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/fragments
This snippet shows the syntax for defining a GraphQL fragment. A fragment starts with the `fragment` keyword, followed by its name, the `on` keyword, and the type it applies to. The fields included in the fragment are listed within curly braces.
```GraphQL
fragment examplePostFragment on Post {
id
title
}
```
--------------------------------
### Default React `index.tsx` file structure
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This code block displays the standard `index.tsx` file, typically found in a React project's `src` folder. It serves as the application's entry point, responsible for rendering the main `App` component into the DOM.
```typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```
--------------------------------
### Initialize Apollo Client for Sanctuary Health GraphQL API
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/setupApolloClient
This code initializes a new ApolloClient instance, configuring it to connect to the Sanctuary Health GraphQL API endpoint. It uses InMemoryCache to manage and cache query results locally, optimizing data fetching.
```typescript
const client = new ApolloClient({
uri: 'https://v4-0-dot-livitay.appspot.com/graphql',
cache: new InMemoryCache(),
});
```
--------------------------------
### Fetching Data with getPosts Query in GraphQL
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/simpleQueries
This example demonstrates how to populate a GraphQL operation with a specific query, "getPosts". It illustrates selecting desired fields ("id" and "title") from the returned data type ("Post") within the query's body. The snippet shows how to retrieve data without optional arguments.
```GraphQL
query exampleOperation {
getPosts {
id
title
}
}
```
--------------------------------
### Configure GraphQL Codegen with TypeScript
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/installingGraphQLCodeGenerator
This configuration file (`codegen.ts`) sets up the GraphQL Codegen tool. It specifies the GraphQL API endpoint, the source files containing GraphQL operations, and the output file for generated types and React Apollo hooks. It also defines the plugins to use (typescript, typescript-operations, typescript-react-apollo) and custom scalar type mappings for better type safety.
```TypeScript
import { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'https://v4-0-dot-livitay.appspot.com/graphql',
documents: ['src/gql/**/*.ts'],
generates: {
'./src/gql.tsx': {
plugins: ['typescript','typescript-operations','typescript-react-apollo']
}
},
config: {
defaultScalarType: 'unknown',
scalars: {
DateTime: 'string'
}
}
}
export default config
```
--------------------------------
### GraphQL Codegen Configuration in TypeScript
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/installingGraphQLCodeGenerator
This TypeScript configuration file (`codegen.ts`) for GraphQL Codegen defines how to generate code from a GraphQL API. It specifies the schema endpoint, the input GraphQL document paths (`src/gql/**/*.ts`), the output file for generated code (`./src/gql.tsx`), and the plugins to use (typescript, typescript-operations, typescript-react-apollo). It also includes custom scalar type mappings, such as `DateTime` to `string`.
```TypeScript
import { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'https://s5.sanctuaryhealth.io/graphql',
documents: ['src/gql/**/*.ts'],
generates: {
'./src/gql.tsx': {
plugins: ['typescript','typescript-operations','typescript-react-apollo']
}
},
config: {
defaultScalarType: 'unknown',
scalars: {
DateTime: 'string'
}
}
}
export default config
```
--------------------------------
### GraphQL Query Operation Framework
Source: https://docs.sanctuaryhealth.io/docs/s5/tutorial/simpleQueries
Demonstrates the basic structure of a GraphQL query operation, including the 'query' keyword and an optional operation name, with a placeholder for supported queries.
```GraphQL
query exampleOperation {
// Supported queries will go here
}
```
--------------------------------
### GraphQL Query 'where' argument with JSON string
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/queriesWithArguments
Example demonstrating how to specify the 'where' argument for a GraphQL query, particularly for SequelizeQuery, using a JSON string to filter by 'id'. Note the requirement for escaping the JSON string.
```JSON
where: "{\"id\": \"c4cf717d-a638-49d8-bbcd-fafd2142d284\"}"
```
--------------------------------
### Use a GraphQL Fragment in a Query
Source: https://docs.sanctuaryhealth.io/docs/s5/tutorial/fragments
This example shows how to incorporate a defined fragment into a GraphQL query. The spread operator `...` followed by the fragment name is used within the target type. It also illustrates that additional fields can be requested alongside the fragment.
```GraphQL
fragment examplePostFragment on PostDetails {
id
title
}
query exampleOperation {
getPostDetails {
...examplePostFragment
description
}
}
```
--------------------------------
### Project Folder Structure for GraphQL Queries and Fragments
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/generatingAndUsingQueries
Illustrates the recommended directory structure for organizing GraphQL fragments and queries within a project, promoting a clean and maintainable codebase for GraphQL Code Generator.
```plaintext
src
└───gql
├───fragments
└───queries
```
--------------------------------
### Use a GraphQL Fragment in a Query
Source: https://docs.sanctuaryhealth.io/docs/v4/tutorial/fragments
This example demonstrates how to use a previously defined GraphQL fragment within a query. The spread operator (`...`) followed by the fragment name is used to include the fragment's fields. Additional fields can also be requested within the same object.
```GraphQL
fragment examplePostFragment on Post {
id
title
}
query exampleOperation {
getPosts {
...examplePostFragment
description
}
}
```
--------------------------------
### Initializing Apollo Client with Concatenated Auth and HTTP Links
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/advancedApolloNetworking
This code demonstrates how to initialize an Apollo Client instance. It configures the client with an `InMemoryCache` and concatenates an `authMiddleware` link with an `httpLink` using the `concat` function, removing the need for a direct `uri`.
```typescript
const client = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, httpLink),
});
```
--------------------------------
### Recommended Folder Structure for GraphQL Assets
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/generatingAndUsingQueries
This snippet outlines the suggested directory organization for GraphQL fragments and queries within a project, facilitating their use with `GraphQL Code Generator` for type generation.
```plaintext
src
└───gql
├───fragments
└───queries
```
--------------------------------
### Recipe Object API Field Reference
Source: https://docs.sanctuaryhealth.io/docs/v4/reference/objects/recipe
Detailed documentation for each field of the `Recipe` GraphQL object, including type, nullability, and description.
```APIDOC
Recipe.id: String! - UUID of recipe
Recipe.language: Language! - Language of recipe
Recipe.format: RecipeFormat! - Unit format of the ingredients (Imperial/ Metric)
Recipe.title: String! - Title of recipe
Recipe.description: String! - Description of recipe
Recipe.method: [String!]! - Preparation steps for recipe
Recipe.methodPreview: [String!]! - Preview of preparation steps for recipe
Recipe.contentValue: Float! - Content value of recipe
Recipe.keywords: [String!] - Keywords for the recipe
Recipe.createdAt: DateTime! - Creation time given as the ISO Date string
Recipe.updatedAt: DateTime! - Last update time given as the ISO Date string
```
--------------------------------
### API Arguments: getCourseDetails Query
Source: https://docs.sanctuaryhealth.io/docs/s5/reference/operations/queries/get-course-details
Detailed documentation for each argument accepted by the `getCourseDetails` GraphQL query, including their types and purpose for filtering and pagination.
```APIDOC
getCourseDetails.where: CourseDetailsWhere input
getCourseDetails.limit: Int scalar
Corresponds to the maximum number of items returned. Can be used in conjunction with “Offset” and “Order” to implement pagination.
getCourseDetails.offset: Int scalar
Corresponds to the number of items skipped before the first returned result. Can be used in conjunction with “Limit” and “Order” to implement pagination.
```
--------------------------------
### Run GraphQL Code Generator Command
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/generatingAndUsingQueries
Executes the `npm run gen` command, which triggers the GraphQL Code Generator. This command processes the defined GraphQL queries and fragments to generate TypeScript typings and React hooks, enabling type-safe data interactions in the application.
```bash
npm run gen
```
--------------------------------
### Define GraphQL Query to Get Post Details
Source: https://docs.sanctuaryhealth.io/docs/s5/fullGuide/generatingAndUsingQueries
Defines a GraphQL query named `getPostsOperation` that fetches `PostDetails` based on a `where` clause, utilizing the `postDetailsFragment` for consistent field selection. This query is designed to be processed by GraphQL Code Generator to produce type-safe React hooks for data fetching.
```typescript
import { gql } from "@apollo/client"
export const GRAPHQL = gql`
query getPostsOperation($where: PostDetailsWhere!) {
getPostDetails(where: $where) {
...postDetailsFragment
}
}
`
```
--------------------------------
### AudioMedia GraphQL Type Field Reference
Source: https://docs.sanctuaryhealth.io/docs/s5/reference/types/objects/audio-media
Detailed API documentation for each field of the AudioMedia GraphQL object type, including their types and descriptions. This reference helps understand the purpose and usage of each field.
```APIDOC
AudioMedia:
id: String! (non-null scalar)
Description: UUID of audio
language: Language! (non-null enum)
Description: Language of audio
languageReviewLevel: LanguageReviewLevel! (non-null enum)
Description: Review level of audio
approximateTime: Int! (non-null scalar)
Description: Approximate time to listen to audio
country: [Country!]! (non-null enum)
Description: Specific country audio is produced for
scriptHTML: String (scalar)
Description: Rich text content of audio script given as JSON string of HTML
```
--------------------------------
### GraphQL Enum Definition: FileDetailsParentType
Source: https://docs.sanctuaryhealth.io/docs/v4/reference/enums/file-details-parent-type
This GraphQL enum defines the FileDetailsParentType and lists all its possible values. Each value represents a specific type of parent entity that a file detail can be associated with in the Sanctuary Health API, enabling structured categorization of media and content. Examples include creator, episodePhoto, organizationLogo, and recipe.
```GraphQL
enum FileDetailsParentType {\n creator\n episodePhoto\n episodeMedia\n episodeScript\n organizationPreRollLandscape\n organizationPreRollPortrait\n organizationPostRollLandscape\n organizationPostRollPortrait\n organizationLogo\n postMedia\n postScript\n postParent\n recipe\n recipeParent\n seriesParent\n}
```
--------------------------------
### API Documentation for Post Object Fields
Source: https://docs.sanctuaryhealth.io/docs/v4/reference/objects/post
Detailed documentation for each field of the `Post` object, including its type, nullability, and a brief description of its purpose. This provides clarity on the data structure and expected values for each field.
```APIDOC
Post Object Fields:
id: String! - UUID of post
language: Language! - Language of post
title: String! - Title of post
contentFormat: ContentFormat! - Format of content
approximateTime: Int! - Approximate consumption time for post given in minutes
description: String! - Description of post
content: String - Rich text content of post given as JSON string of raw DraftJs content state
contentHTML: String - Rich text content of post given as JSON string of HTML
contentHTMLPreview: String - Rich text preview of content of post given as JSON string of HTML
contentValue: Float! - Content value of post
topic: [Topic!] - Topic of the post
icd10: [String!] - No description provided.
keywords: [String!] - No description provided.
learningOutcome: String - No description provided.
createdAt: DateTime! - No description provided.
updatedAt: DateTime! - No description provided.
deletedAt: DateTime - No description provided.
postParentId: String! - No description provided.
creatorId: String! - No description provided.
postParent: PostParent! - No description provided.
creator: Creator! - No description provided.
mediaFileDetailsList: [FileDetails!]! - No description provided.
scriptFileDetails: FileDetails - No description provided.
```
--------------------------------
### Importing Apollo Client Modules for Link Concatenation
Source: https://docs.sanctuaryhealth.io/docs/v4/fullGuide/advancedApolloNetworking
This snippet shows the essential imports from `@apollo/client` required for setting up an Apollo Client. It includes `ApolloClient`, `InMemoryCache`, `ApolloProvider`, `ApolloLink`, `HttpLink`, and `concat` for link management.
```typescript
import { ApolloClient, InMemoryCache, ApolloProvider, ApolloLink, HttpLink, concat } from '@apollo/client';
```
--------------------------------
### Sanctuary Health s5 API Structure Overview
Source: https://docs.sanctuaryhealth.io/docs/s5/reference/types/inputs/article-media-where
This snippet outlines the hierarchical structure of the Sanctuary Health s5 API, listing its main categories such as operations (directives, queries) and various data types (directives, enums, inputs, objects, scalars, unions) along with specific examples within each category.
```APIDOC
Operations:
Directives:
- include
Queries:
- get-card-pack-details
Types:
Directives:
- deprecated
Enums:
- accent
Inputs:
- AccentAttributeWhereOperators
- ArticleMediaWhere
- AudioMediaWhere
- BooleanAttributeWhereOperators
- CaptionWhere
- CardPackDetailsWhere
- CardPackWhere
- CardWhere
- CategoryArrayAttributeWhereOperators
- CountryArrayAttributeWhereOperators
- CourseDetailsWhere
- CourseItemWhere
- CourseWhere
- CreatorWhere
- DubbWhere
- GenderAttributeWhereOperators
- IngredientListItemWhere
- LanguageAttributeWhereOperators
- MediaUnionWhere
- NumberAttributeWhereOperators
- PostDetailsWhere
- PostMediaTypeAttributeWhereOperators
- PostWhere
- RecipeDetailsWhere
- RecipeFormatAttributeWhereOperators
- RecipeTagArrayAttributeWhereOperators
- RecipeUnitAttributeWhereOperators
- RecipeWhere
- StringArrayAttributeWhereOperators
- StringAttributeWhereOperators
- TopicArrayAttributeWhereOperators
- UUIDAttributeWhereOperators
- VideoMediaWhere
Objects:
- article-media-version
Scalars:
- boolean
Unions:
- course-item-content-union
```
--------------------------------
### GraphQL `Course` Object Fields Reference
Source: https://docs.sanctuaryhealth.io/docs/s5/reference/types/objects/course
Provides detailed descriptions for each field of the `Course` GraphQL object, specifying their types, nullability, and purpose, such as `id` (UUID), `universalTitle` (course name), `contentValue`, `category`, `topic`, and timestamps.
```APIDOC
Course.id: String!
Description: UUID of course
Course.universalTitle: String!
Description: Universal title of course
Course.contentValue: Int!
Description: Content value of course
Course.category: [Category!]!
Description: List of categories course is included in
Course.topic: [ContentTopic!]!
Description: Topic of the course
Course.createdAt: DateTimeISO!
Description: Creation time given as the ISO Date string
Course.updatedAt: DateTimeISO!
Description: Last update time given as the ISO Date string
```
--------------------------------
### VideoMedia Object Fields API Reference
Source: https://docs.sanctuaryhealth.io/docs/s5/reference/types/objects/video-media
Detailed documentation for specific fields of the `VideoMedia` GraphQL type, including type, nullability, and description as provided in the source.
```APIDOC
VideoMedia Fields:
id:
Type: String! (non-null scalar)
Description: UUID of video
language:
Type: Language! (non-null enum)
Description: Language of video
languageReviewLevel:
Type: LanguageReviewLevel! (non-null enum)
Description: Review level of video
approximateTime:
Type: Int! (non-null scalar)
Description: Approximate time to watch video
country:
Type: [Country!]! (non-null enum)
Description: Specific country video is produced for
scriptHTML:
Type: String (scalar)
Description: Rich text content of video given as JSON string of HTML
```