### Install and Run F1 GraphQL API Source: https://github.com/francostino/f1-graphql-api/blob/main/README.md This snippet outlines the steps to clone the repository, configure environment variables, set up the database using Lando, install dependencies, build the Prisma client, and start the development server. It also includes instructions for exporting the database. ```bash # Clone the repository git clone git@github.com:FrancoStino/F1-GraphQL.git # Navigate to the project directory cd F1-GraphQL # Configure your environment cp .env.example .env # Edit .env with your database connection string # Start Lando lando start # Import from ZIP archive lando db-import db/f1db-sql-mysql-single-inserts.zip # Install dependencies yarn install # Generate Prisma client yarn build # Start development server yarn dev ``` ```bash lando db-export ``` -------------------------------- ### Prisma Schema Setup for Database and Resolvers (Prisma) Source: https://context7.com/francostino/f1-graphql-api/llms.txt Defines the database connection and configuration for Prisma client and GQLoom resolver generation. This file specifies the data source, generators for Prisma client and GQLoom, and example environment variable configuration. The build process involves pulling the schema, formatting names, and generating code. ```prisma generator client { provider = "prisma-client-js" output = "../prisma/generated/client" } generator gqloom { provider = "prisma-gqloom" output = "../prisma/generated/gqloom" } datasource db { provider = "mysql" url = env("DATABASE_URL") } // Example .env configuration: // DATABASE_URL="mysql://user:password@localhost:3306/f1db" // Build process: // 1. yarn pull - Introspect database and generate schema // 2. prisma-case-format - Convert to camelCase naming // 3. prisma generate - Generate Prisma client and GQLoom resolvers ``` -------------------------------- ### Express Application Setup and Server Initialization Source: https://context7.com/francostino/f1-graphql-api/llms.txt Creates and configures an Express application, disabling the 'x-powered-by' header and setting up static file serving for '/assets' and '/public' directories. It also initializes an HTTP server. ```typescript // src/servers/Express.ts import express from 'express'; import { createServer } from 'node:http'; import path from 'path'; const app = express(); app.disable('x-powered-by'); // Serve static assets app.use('/assets', express.static(path.join(__dirname, '../../assets'))); app.use('/public', express.static(path.join(__dirname, '../../public'))); const server = createServer(app); export function getExpressApp() { return { app, server }; } export function startServer(port: number) { server.listen(port, () => { console.info(`๐Ÿš€ Server running on http://localhost:${port}`); }); return server; } // Usage: startServer(4000) ``` -------------------------------- ### Example GraphQL Queries Source: https://github.com/francostino/f1-graphql-api/blob/main/README.md Illustrative GraphQL queries to demonstrate how to retrieve data from the F1 API. ```APIDOC ## Example Queries ### Get first ten Drivers ```graphql query Drivers { findManyDriver(take: 10) { id firstName lastName name fullName gender dateOfBirth } } ``` ### Find Race Results for a Specific Grand Prix This section is incomplete in the provided text. ``` -------------------------------- ### Configure GraphQL Yoga Server with Custom GraphiQL Source: https://context7.com/francostino/f1-graphql-api/llms.txt Sets up GraphQL Yoga server with a custom GraphiQL interface, including custom styling and a default example query. It is configured to serve on the '/graphql' endpoint. ```typescript // src/servers/GraphQL-Yoga.ts import { renderGraphiQL } from "@graphql-yoga/render-graphiql"; import { createYoga } from "graphql-yoga"; import { schema } from "../resolvers/resolvers"; import { getExpressApp } from './Express'; function customRenderGraphiQL() { const html = renderGraphiQL({ title: 'F1 GraphQL Yoga', defaultQuery: `query Drivers { findManyDriver(take: 10) { id firstName lastName fullName gender dateOfBirth } }` }); return html.replace( '', ` ` ); } const yoga = createYoga({ schema, graphqlEndpoint: '/graphql', renderGraphiQL: () => customRenderGraphiQL(), landingPage: false }); export function initYogaServer() { const { app } = getExpressApp(); app.use('/graphql', yoga); console.info(`๐Ÿš€ GraphQL Yoga Server ready at: /graphql`); } ``` -------------------------------- ### GraphQL Query for Paginated Constructor Standings Source: https://context7.com/francostino/f1-graphql-api/llms.txt An example GraphQL query to fetch paginated constructor data, ordered by name. This query demonstrates how to implement pagination using 'skip' and 'take' arguments in GraphQL. ```graphql query ConstructorStandings { findManyConstructor( skip: 0 take: 10 orderBy: { name: asc } ) { id name nationality url } } ``` -------------------------------- ### Access Apollo Server Endpoint with cURL Source: https://context7.com/francostino/f1-graphql-api/llms.txt Illustrates querying for F1 race data using the Apollo Server endpoint via cURL. This example fetches race year, turns, laps, date, and name for races in 2023, demonstrating filtered data retrieval. Assumes the API is running. ```bash # Access Apollo Sandbox curl http://localhost:4000/apollo # Query race results curl -X POST http://localhost:4000/apollo \ -H "Content-Type: application/json" \ -d '{ "query": "query { findManyRace(take: 5, where: { year: { equals: 2023 } }) { year turns laps date name } }" }' # Response { "data": { "findManyRace": [ { "year": 2023, "turns": 15, "laps": 57, "date": "2023-03-05", "name": "Bahrain Grand Prix" } ] } } ``` -------------------------------- ### GraphQL Query for Filtering Drivers by Nationality Source: https://context7.com/francostino/f1-graphql-api/llms.txt An example GraphQL query to retrieve a list of drivers filtered by their nationality. It also applies a limit to the number of results and orders them by date of birth. This query demonstrates basic filtering and ordering capabilities. ```graphql query DriversByNationality { findManyDriver( where: { nationality: { equals: "British" } } take: 5 orderBy: { dateOfBirth: desc } ) { id firstName lastName fullName nationality dateOfBirth code permanentNumber } } ``` -------------------------------- ### Server Initialization in TypeScript Source: https://context7.com/francostino/f1-graphql-api/llms.txt The main entry point for the F1 GraphQL API application. This TypeScript code orchestrates the startup of the landing page, Apollo Server, GraphQL Yoga, and the Express HTTP server, binding them to a specified port. It includes error handling for the startup process. ```typescript // src/index.ts import { initApolloServer } from "./servers/ApolloServer"; import { startServer } from "./servers/Express"; import { initYogaServer } from "./servers/GraphQL-Yoga"; import { setupLandingPage } from "./servers/LandingPage"; const PORT = process.env.PORT ? parseInt(process.env.PORT) : 4000; async function startApp() { console.info("โœจ Starting F1 GraphQL Servers..."); // Setup landing page with rate limiting setupLandingPage(); // Initialize Apollo Server (async) await initApolloServer(); // Initialize Yoga Server (sync) initYogaServer(); // Start unified HTTP server on port 4000 startServer(PORT); } startApp().catch((err: unknown) => { console.error("Failed to start servers:", err); process.exit(1); }); ``` -------------------------------- ### Initialize Apollo Server with Plugins and Middleware Source: https://context7.com/francostino/f1-graphql-api/llms.txt Initializes Apollo Server, enabling caching, introspection, and a local landing page. It is mounted on the '/apollo' endpoint with CORS and JSON middleware. ```typescript // src/servers/ApolloServer.ts import { ApolloServer } from '@apollo/server'; import { expressMiddleware } from '@apollo/server/express4'; import { ApolloServerPluginCacheControl } from '@apollo/server/plugin/cacheControl'; import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default'; import cors from 'cors'; import express from 'express'; import { schema } from '../resolvers/resolvers'; import { getExpressApp } from './Express'; const serverApollo = new ApolloServer({ schema, introspection: true, plugins: [ ApolloServerPluginLandingPageLocalDefault({ embed: true, includeCookies: true, }), ApolloServerPluginCacheControl({ defaultMaxAge: 5, // 5 seconds cache }), ], }); export async function initApolloServer() { await serverApollo.start(); const { app } = getExpressApp(); app.use( '/apollo', cors(), express.json(), expressMiddleware(serverApollo, { context: ({ req }) => Promise.resolve({ req }), }), ); console.info(`๐Ÿš€ Apollo Server ready at: /apollo`); } ``` -------------------------------- ### Configure Landing Page with Rate Limiting Source: https://context7.com/francostino/f1-graphql-api/llms.txt Sets up the main landing page route ('/'). It applies rate limiting to protect against excessive requests, allowing a maximum of 10 requests per 15-minute window. The page dynamically injects the current year. ```typescript // src/servers/LandingPage.ts import rateLimit from 'express-rate-limit'; import fs from 'fs'; import path from 'path'; import { getExpressApp } from './Express'; export function setupLandingPage() { const { app } = getExpressApp(); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 10, // 10 requests per window message: 'Too many attempts, try again later.' }); app.get('/', limiter, (req, res) => { const filePath = path.join('public/index.html'); fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.error('Error reading index.html:', err); return res.status(500).send('Error loading the page'); } // Dynamic year injection const html = data.replace('', new Date().getFullYear().toString()); res.setHeader('Content-Type', 'text/html'); res.send(html); }); }); console.info(`๐Ÿ  Landing page setup at: /`); } ``` -------------------------------- ### Landing Page Endpoint Source: https://context7.com/francostino/f1-graphql-api/llms.txt The main landing page of the API. It provides navigation links to the GraphQL interfaces and is protected by a rate limiter. ```APIDOC ## Landing Page Endpoint ### Description The main welcome page for the F1 GraphQL API. It offers navigation links to the GraphQL interfaces (GraphQL Yoga and Apollo Server) and is protected by rate limiting. ### Method GET ### Endpoint `/` ### Parameters None ### Request Example ```bash curl http://localhost:4000/ ``` ### Response #### Success Response (200) - **HTML Page** - Returns an HTML page with links to the available GraphQL endpoints. #### Response Example (Response is an HTML page, not JSON) ``` -------------------------------- ### Prisma Client Singleton for Database Operations Source: https://context7.com/francostino/f1-graphql-api/llms.txt Provides a singleton instance of the Prisma Client for database operations. This client is auto-generated from the schema and offers type-safe access to all F1 data tables. ```typescript // src/providers/prismaClient.ts import { PrismaClient } from "../../prisma/generated/client"; const db = new PrismaClient(); export default db; // Used by PrismaResolverFactory in resolvers.ts // Provides type-safe database access to all F1 tables: // - drivers, races, circuits, constructors // - results, standings, lap times, pit stops // - seasons, qualifying, sprint races, etc. ``` -------------------------------- ### GraphQL Yoga Endpoint Source: https://context7.com/francostino/f1-graphql-api/llms.txt The primary GraphQL interface, powered by GraphQL Yoga. It includes an interactive GraphiQL playground for easy query testing and exploration. ```APIDOC ## GraphQL Yoga Endpoint ### Description This endpoint provides the main GraphQL interface using GraphQL Yoga, featuring an interactive GraphiQL playground for testing queries. ### Method POST, GET ### Endpoint `/graphql` ### Parameters #### Query Parameters None #### Request Body - **query** (String) - Required - The GraphQL query string. - **variables** (Object) - Optional - Variables for the GraphQL query. ### Request Example ```bash curl -X POST http://localhost:4000/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query { findManyDriver(take: 10) { id firstName lastName fullName gender dateOfBirth } }" }' ``` ### Response #### Success Response (200) - **data** (Object) - Contains the result of the GraphQL query. #### Response Example ```json { "data": { "findManyDriver": [ { "id": 1, "firstName": "Lewis", "lastName": "Hamilton", "fullName": "Lewis Carl Davidson Hamilton", "gender": "M", "dateOfBirth": "1985-01-07" } ] } } ``` ``` -------------------------------- ### Apollo Server Endpoint Source: https://context7.com/francostino/f1-graphql-api/llms.txt An alternative GraphQL interface implemented with Apollo Server. It includes Apollo Sandbox for advanced query building and testing capabilities. ```APIDOC ## Apollo Server Endpoint ### Description This endpoint offers an alternative GraphQL interface using Apollo Server, complete with Apollo Sandbox for advanced query creation and testing. ### Method POST, GET ### Endpoint `/apollo` ### Parameters #### Query Parameters None #### Request Body - **query** (String) - Required - The GraphQL query string. - **variables** (Object) - Optional - Variables for the GraphQL query. ### Request Example ```bash curl -X POST http://localhost:4000/apollo \ -H "Content-Type: application/json" \ -d '{ "query": "query { findManyRace(take: 5, where: { year: { equals: 2023 } }) { year turns laps date name } }" }' ``` ### Response #### Success Response (200) - **data** (Object) - Contains the result of the GraphQL query. #### Response Example ```json { "data": { "findManyRace": [ { "year": 2023, "turns": 15, "laps": 57, "date": "2023-03-05", "name": "Bahrain Grand Prix" } ] } } ``` ``` -------------------------------- ### GraphQL Schema File Generator (TypeScript) Source: https://context7.com/francostino/f1-graphql-api/llms.txt Utility script to export the complete GraphQL schema to a '.graphql' file. This is useful for documentation and tooling purposes. It uses 'graphql' for schema printing and 'node:fs'/'node:path' for file operations. The script assumes a 'schema' object is imported from '../resolvers/resolvers'. ```typescript import { printSchema } from "graphql"; import * as fs from "node:fs"; import * as path from "node:path"; import { schema } from "../resolvers/resolvers"; // Generate schema.graphql file fs.writeFileSync( path.join(__dirname, "schema.graphql"), printSchema(schema) ); // Run with: yarn generate-schema.graphql // Outputs complete SDL schema for all F1 data types and queries ``` -------------------------------- ### Access GraphQL Yoga Endpoint with cURL Source: https://context7.com/francostino/f1-graphql-api/llms.txt Demonstrates how to access the GraphQL Yoga endpoint and query for F1 drivers using cURL. This showcases the API's ability to retrieve driver details like ID, name, and date of birth. It requires a running instance of the API. ```bash # Access the GraphiQL interface curl http://localhost:4000/graphql # Query drivers with GraphQL curl -X POST http://localhost:4000/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query { findManyDriver(take: 10) { id firstName lastName fullName gender dateOfBirth } }" }' # Response { "data": { "findManyDriver": [ { "id": 1, "firstName": "Lewis", "lastName": "Hamilton", "fullName": "Lewis Carl Davidson Hamilton", "gender": "M", "dateOfBirth": "1985-01-07" } ] } } ``` -------------------------------- ### GraphQL Schema Generation with GQLoom and Prisma Source: https://context7.com/francostino/f1-graphql-api/llms.txt Dynamically generates a GraphQL schema from Prisma models using GQLoom. This TypeScript code defines query resolvers for all database entities, enabling queries like `findManyDriver` and `findManyRace`. It supports filtering, pagination, ordering, and nested relations. ```typescript // src/resolvers/resolvers.ts import { weave } from "@gqloom/core"; import { PrismaResolverFactory } from "@gqloom/prisma"; import * as Resolvers from "../../prisma/generated/gqloom"; import db from "../providers/prismaClient"; import { prismaWeaverConfig } from "../utils/PrismaWeaver.config"; // Generate schema with query resolvers for all Prisma models export const schema = weave( ...Object.values(Resolvers).map(model => new PrismaResolverFactory(model, db).queriesResolver() ), prismaWeaverConfig ); // Example usage in queries: // findManyDriver - Query multiple drivers // findUniqueDriver - Query single driver by unique field // findFirstDriver - Query first matching driver // findManyRace - Query multiple races // Supports: filtering, pagination (take/skip), ordering, nested relations ``` -------------------------------- ### F1 GraphQL API Endpoints Source: https://github.com/francostino/f1-graphql-api/blob/main/README.md Access the F1 GraphQL API through different interfaces for testing and development. ```APIDOC ## API Endpoints Once running, access your GraphQL API through: | Endpoint | URL | Description | |----------|-----|-------------| | ๐Ÿ  **Landing Page** | `http://localhost:4000/` | Main welcome page with links | | ๐Ÿงช **GraphQL Yoga** | `http://localhost:4000/graphql` | GraphiQL interface for testing | | ๐Ÿš€ **Apollo Server** | `http://localhost:4000/apollo` | Apollo Sandbox environment | ``` -------------------------------- ### GraphQL Query for First Ten Drivers Source: https://github.com/francostino/f1-graphql-api/blob/main/README.md This GraphQL query retrieves the first ten drivers from the F1 database, including their ID, first name, last name, full name, gender, and date of birth. It demonstrates a basic query to fetch driver information. ```graphql query Drivers { findManyDriver(take: 10) { id firstName lastName name fullName gender dateOfBirth } } ``` -------------------------------- ### Find Race Results Source: https://github.com/francostino/f1-graphql-api/blob/main/README.md This endpoint allows you to query for race results. You can specify the number of results to retrieve using the `take` argument. ```APIDOC ## Query Race Results ### Description Retrieves a list of race results, with an option to limit the number of results returned. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body ```json { "query": "query Race($take: Int = 50) {\n findManyRace(take: $take) {\n year\n turns\n laps\n }\n}", "variables": { "take": 50 } } ``` ### Request Example ```json { "query": "query Race($take: Int = 50) {\n findManyRace(take: $take) {\n year\n turns\n laps\n }\n}", "variables": { "take": 10 } } ``` ### Response #### Success Response (200) - **data** (object) - Contains the race results. - **findManyRace** (array) - An array of race result objects. - **year** (integer) - The year of the Grand Prix. - **turns** (integer) - The number of turns in the circuit. - **laps** (integer) - The number of laps in the race. #### Response Example ```json { "data": { "findManyRace": [ { "year": 2023, "turns": 14, "laps": 71 }, { "year": 2022, "turns": 14, "laps": 57 } ] } } ``` ``` -------------------------------- ### Prisma Weaver Configuration for GraphQL Date Type (TypeScript) Source: https://context7.com/francostino/f1-graphql-api/llms.txt Configures Prisma Weaver to map Prisma's DateTime type to GraphQL's Date scalar type. This ensures consistent date handling when generating the GraphQL schema. It requires the '@gqloom/prisma' package and 'graphql-scalars'. ```typescript import { PrismaWeaver } from '@gqloom/prisma'; import { GraphQLDate } from 'graphql-scalars'; export const prismaWeaverConfig = PrismaWeaver.config({ presetGraphQLType: (type) => { if (type === 'DateTime') { return GraphQLDate; } }, }); // Ensures all Prisma DateTime fields are exposed as GraphQL Date type // Used in schema weaving process for consistent date handling ``` -------------------------------- ### GraphQL Query for Race Results with Circuit Details Source: https://context7.com/francostino/f1-graphql-api/llms.txt This GraphQL query retrieves race results for a specific year and name containing 'Monaco', fetching nested circuit details. It demonstrates querying for specific races and accessing related data through nested objects. ```graphql query RaceResultsWithDrivers { findManyRace( where: { year: { equals: 2023 } name: { contains: "Monaco" } } take: 1 ) { id name year date laps circuit { name location country } } } ``` -------------------------------- ### Query Race Results - GraphQL Source: https://github.com/francostino/f1-graphql-api/blob/main/README.md This GraphQL query retrieves a list of race results, including the year, number of turns, and laps for up to 50 races. It's a basic query for fetching core race data. ```graphql query Race { findManyRace(take: 50) { year turns laps } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.