### REST Index/List Endpoint Example Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/overview.md Demonstrates the structure of a GET request to an index or list endpoint and its typical JSON response. ```http GET /api/2014/{resource} ``` ```json { "count": 5, "results": [ { "index": "aboleth", "name": "Aboleth", "url": "/api/2014/monsters/aboleth" } ] } ``` -------------------------------- ### Apollo Server Middleware Setup Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/middleware-utilities.md Creates and configures an Apollo Server instance for a GraphQL endpoint. It should be started and then used with expressMiddleware, providing context with request headers and language. ```typescript async function createApolloMiddleware( schema: GraphQLSchema ): Promise ``` ```typescript const apollo = await createApolloMiddleware(schema) await apollo.start() app.use( '/graphql/2014', expressMiddleware(apollo, { context: async ({ req }) => ({ token: req.headers.token, lang: req.lang }) }) ) ``` -------------------------------- ### REST Single Resource Endpoint Example Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/overview.md Illustrates the GET request format for a single resource endpoint. ```http GET /api/2014/{resource}/{index} ``` -------------------------------- ### Configure Localstack for S3 Mocking Source: https://github.com/5e-bits/5e-srd-api/blob/main/README.md Commands to set up and start localstack to mock AWS S3 for testing image resources locally. Ensure localstack, awscli, and awslocal are installed. ```shell export AWS_CONFIG_ENV=localstack_dev localstack start awslocal s3api create-bucket --bucket dnd-5e-api-images awslocal s3 cp aboleth.png s3://dnd-5e-api-images/monsters/ npm run dev ``` -------------------------------- ### Get Single Class Response Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Example response when retrieving a single class. Includes detailed information such as hit die, class levels, spellcasting, and subclasses. ```json Complete Class object including: - Basic: `index`, `name`, `hit_die`, `class_levels`, `multi_classing` - Features: `features`, `spellcasting` - Subclasses: `subclasses` ``` -------------------------------- ### Environment Setup Variables Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/INDEX.md Key environment variables required for local development of the 5e SRD API. ```bash NODE_ENV=development MONGODB_URI=mongodb://localhost/5e-database REDIS_URL=redis://localhost:6379 RATE_LIMIT_WINDOW_MS=1000 RATE_LIMIT_MAX=50 ``` -------------------------------- ### Content-Language Header Example Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Example of the `Content-Language` header in an API response, indicating the language of the returned content. ```http Content-Language: es ``` -------------------------------- ### List Classes Response Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Example response when listing all available classes. Returns a list of class objects, each containing basic information and a URL. ```json List of class objects with `index`, `name`, `hit_die`, `url` ``` -------------------------------- ### Get Class Levels Response Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Example response for retrieving all levels of a specific class. Returns an array of Level objects, sorted by level. ```json Array of Level objects sorted by level (1-20) ``` -------------------------------- ### Quick REST Calls Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/INDEX.md Examples of making quick REST calls to retrieve spell and monster data. Supports filtering by level and language. ```bash # Get all 5th level spells curl "http://localhost:3000/api/2014/spells?level=5" ``` ```bash # Get specific monster curl http://localhost:3000/api/2014/monsters/aboleth ``` ```bash # Get in Spanish curl "http://localhost:3000/api/2014/spells?lang=es" ``` -------------------------------- ### Example Query for Level Data Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/database-models.md Demonstrates how to query for a specific class level progression using MongoDB syntax. ```javascript db.levels.findOne({ "class.url": "/api/2014/classes/wizard", level: 5 }) // Returns Wizard level 5 progression ``` -------------------------------- ### GraphQL Query for Equipment Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Example GraphQL query to retrieve equipment details, with filtering by name and options for pagination. Demonstrates querying cost, weight, properties, and rarity. ```graphql query EquipmentExample { equipment(name: "Sword") { index name equipment_category { index name } cost { quantity unit } weight properties { index name } rarity } } ``` -------------------------------- ### List Monsters with Query Parameters Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Example of how to use query parameters to filter the list of monsters by name and challenge rating. This demonstrates a practical application of the filtering capabilities. ```bash curl "http://localhost:3000/api/2014/monsters?name=dragon&challenge_rating=10" ``` -------------------------------- ### GraphQL Pagination Example Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-resolvers.md Use 'skip' and 'limit' arguments in GraphQL queries to implement pagination for list queries. Note that a separate query is required for the total count. ```graphql query { monsters(skip: 20, limit: 10) { # Get items 21-30 name } } ``` -------------------------------- ### Get Specific Class Level Response Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Example response for a single level of a specific class. Provides details on features, ability score improvements, and spell slots for that level. ```json Single Level object with features, ability score improvements, spell slots for that level ``` -------------------------------- ### Run API with Docker Compose Source: https://github.com/5e-bits/5e-srd-api/blob/main/README.md Starts the API service using Docker Compose. This command builds the image if necessary and runs the container. ```shell docker compose up --build ``` -------------------------------- ### Get Single Background Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific background by its index. ```APIDOC ## GET /api/2014/backgrounds/{index} ### Description Retrieves a specific background by its index. ### Method GET ### Endpoint /api/2014/backgrounds/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the background to retrieve. ### Response #### Success Response (200) - **background** (object) - The background object. ``` -------------------------------- ### Error Response: 404 Not Found Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/overview.md Example of a JSON response for a 404 Not Found error when a resource does not exist. ```json { "message": "Not found" } ``` -------------------------------- ### Pagination with Skip and Limit Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Explains how to paginate query results using the `skip` and `limit` arguments to control the number of items returned and the starting point of the results. ```APIDOC ## Pagination Arguments Use `skip` and `limit` for paginating query results. ```graphql query { monsters(skip: 0, limit: 20) { index name } } ``` - **`skip`** (Int): The number of items to skip from the beginning of the result set. - **`limit`** (Int): The maximum number of items to return in the query. ``` -------------------------------- ### Get Single Equipment Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific equipment item by its index. ```APIDOC ## GET /api/2014/equipment/{index} ### Description Retrieves a specific equipment item by its index. ### Method GET ### Endpoint /api/2014/equipment/{index} ### Response #### Success Response (200) - **index** (string) - The index of the equipment. - **name** (string) - The name of the equipment. - **equipment_category** (string) - The category the equipment belongs to. - **cost** (object) - The cost of the equipment. - **damage** (object) - Damage details if the equipment is a weapon. - **armor_class** (object) - Armor class details if the equipment is armor. - **weight** (number) - The weight of the equipment. - **properties** (array) - Special properties of the equipment. - **rarity** (string) - The rarity of the equipment. - **requires_attunement** (boolean) - Whether the equipment requires attunement. ``` -------------------------------- ### GraphQL Query for Classes Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Example GraphQL query to fetch class information, with filtering by name and options for pagination. Shows how to retrieve details about proficiencies, spellcasting, features, and subclasses. ```graphql query ClassesExample { classes(name: "Wizard") { index name hitDie proficiencies { index name } spellcasting { spellcastingAbility { name } cantripsKnown { level value } } features { index name level } subclasses { index name } } } ``` -------------------------------- ### Download Monster Image using cURL Source: https://github.com/5e-bits/5e-srd-api/blob/main/README.md Example of how to download a monster image using cURL. This command fetches the image from the API and saves it locally. ```shell curl http://localhost:3000/api/2014/monsters/aboleth.png --output downloaded-aboleth.png ``` -------------------------------- ### GraphQL Sorting Example Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Use this structure to define sorting parameters in GraphQL queries. Supports multiple levels of sorting with specified directions. ```graphql order: { by: NAME, direction: ASC, thenBy: { by: FULL_NAME, direction: DESC } } ``` -------------------------------- ### Get All Monsters (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Use this endpoint to retrieve a list of all monsters available in the API. ```bash curl http://localhost:3000/api/2014/monsters ``` -------------------------------- ### Get Single Resource (GraphQL) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieve detailed information for a single monster, including its actions. ```graphql query { monster(index: "aboleth") { name size type hitPoints actions { name desc } } } ``` -------------------------------- ### Pull Latest Database Image Source: https://github.com/5e-bits/5e-srd-api/blob/main/README.md Use this command to pull the latest version of the database image. Ensure Docker is installed and running. ```shell docker compose pull ``` -------------------------------- ### Redis Client Methods Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/middleware-utilities.md Provides basic methods for interacting with a Redis client instance for caching operations. Includes getting, setting, and deleting values by key. ```typescript const cached = await redisClient.get(key) // Get value await redisClient.set(key, value) // Set value await redisClient.del(key) // Delete key ``` -------------------------------- ### Paginate Monster Results Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Example query to retrieve a paginated list of monsters, skipping the first 0 items and limiting the results to 20. ```graphql query { monsters(skip: 0, limit: 20) { index name } } ``` -------------------------------- ### Get Spell Response Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Example JSON response when requesting a single spell. Includes core details, components, effects, damage, saving throws, and related classes. ```json { "count": 2, "results": [ { "index": "magic-missile", "name": "Magic Missile", "level": 1, "url": "/api/2014/spells/magic-missile" } ] } ``` -------------------------------- ### Fetch Skills via Field Resolver Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Example query to retrieve skills associated with ability scores. The 'skills' field is resolved separately. ```graphql query { abilityScores { skills { # Field resolver fetches related Skills index name abilityScore { name } } } } ``` -------------------------------- ### Get Monsters by Challenge Rating (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Filter monsters by specifying one or more challenge ratings. Separate multiple CRs with commas. ```bash curl "http://localhost:3000/api/2014/monsters?challenge_rating=5,6" ``` -------------------------------- ### Configure SRD Models Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/middleware-utilities.md Applies consistent Typegoose configuration to SRD models. Use this decorator to ensure uniform model setup. ```typescript @ObjectType() @srdModelOptions('2014-spells') export class Spell { @prop() name!: string } ``` -------------------------------- ### Error Response: 400 Bad Request Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/overview.md Example of a JSON response for a 400 Bad Request error, detailing invalid query parameters. ```json { "error": "Invalid query parameters", "details": [ { "code": "invalid_type", "expected": "number", "received": "string", "path": ["challenge_rating"], "message": "Expected number, received string" } ] } ``` -------------------------------- ### Monster Index Response Format Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Example JSON structure for the response when listing monsters, including count and a list of results with index, name, and URL. ```json { "count": 5, "results": [ { "index": "aboleth", "name": "Aboleth", "url": "/api/2014/monsters/aboleth" } ] } ``` -------------------------------- ### Get Single Trait Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific trait by its index. ```APIDOC ## GET /api/2014/traits/{index} ### Description Retrieves a specific trait by its index. ### Method GET ### Endpoint /api/2014/traits/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the trait to retrieve. ### Response #### Success Response (200) - **trait** (object) - The trait object. ``` -------------------------------- ### REST API Endpoints Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md This section details the base URLs for accessing the REST API in different versions and provides examples of list and single item retrieval patterns. ```APIDOC ## REST API Endpoints ### Base URLs - **REST 2014:** `http://localhost:3000/api/2014` - **REST 2024:** `http://localhost:3000/api/2024` ### REST List/Show Pattern ``` GET /api/2014/{resource} # List GET /api/2014/{resource}/{index} # Single item ``` ``` -------------------------------- ### SimpleController - show Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Generic show implementation to find and return a single resource by its index. It validates parameters, finds the document, handles not found errors, applies translations, and sets the Content-Language header. ```APIDOC ## GET /resource/{index} ### Description Retrieves a single resource by its index. ### Method GET ### Endpoint /resource/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The index of the resource to retrieve. ### Response #### Success Response (200) - **resource** (object) - The full object of the requested resource. ### Response Example { "index": "strength", "name": "Strength", "full_name": "Strength Score", "desc": [ "Your Strength (STR) describes physical power, athleticism, and the extent to which you are hampered by burden orclimbing." ], "url": "/api/v2/ability-scores/strength" } ``` -------------------------------- ### Get Single Skill Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific skill by its index. ```APIDOC ## GET /api/2014/skills/{index} ### Description Retrieves a specific skill by its index. ### Method GET ### Endpoint /api/2014/skills/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the skill to retrieve. ### Response #### Success Response (200) - **skill** (object) - The skill object. ``` -------------------------------- ### GraphQL Query for Ability Scores Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Example GraphQL query to retrieve ability scores, with options to filter by name and include related skills. Demonstrates basic filtering and nested data retrieval. ```graphql query AbilityScoresExample { abilityScores(name: "Strength") { index name fullName description skills { index name } } } ``` -------------------------------- ### GraphQL Query for Spells Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-api.md Example GraphQL query to fetch spells, allowing filtering by name, level, and school, with sorting and pagination options. Shows how to query for multiple spell levels. ```graphql query SpellsExample { spells( name: "Fireball" level: [3, 4] order: { by: NAME, direction: ASC } limit: 10 ) { index name level school { index name } castingTime duration concentration components description classes { index name } } } ``` -------------------------------- ### Get Single Rule Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific rule by its index. ```APIDOC ## GET /api/2014/rules/{index} ### Description Retrieves a specific rule by its index. ### Method GET ### Endpoint /api/2014/rules/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the rule to retrieve. ### Response #### Success Response (200) - **rule** (object) - The rule object. ``` -------------------------------- ### Get Single Proficiency Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific proficiency by its index. ```APIDOC ## GET /api/2014/proficiencies/{index} ### Description Retrieves a specific proficiency by its index. ### Method GET ### Endpoint /api/2014/proficiencies/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the proficiency to retrieve. ### Response #### Success Response (200) - **proficiency** (object) - The proficiency object. ``` -------------------------------- ### GraphQL Schema Building Configuration Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-resolvers.md Configure GraphQL schemas at server startup using 'buildSchema'. Key options include 'resolvers', 'globalMiddlewares', and 'validate' settings. ```typescript import { buildSchema } from 'type-graphql'; import { TranslationMiddleware } from './translation.middleware'; import { resolversArray } from './resolvers'; const schema = await buildSchema({ resolvers: resolversArray, globalMiddlewares: [TranslationMiddleware], validate: { forbidUnknownValues: false } }) ``` -------------------------------- ### Get Single Language Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific language by its index. ```APIDOC ## GET /api/2014/languages/{index} ### Description Retrieves a specific language by its index. ### Method GET ### Endpoint /api/2014/languages/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the language to retrieve. ### Response #### Success Response (200) - **language** (object) - The language object. ``` -------------------------------- ### Get Single Feature Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific feature by its index. ```APIDOC ## GET /api/2014/features/{index} ### Description Retrieves a specific feature by its index. ### Method GET ### Endpoint /api/2014/features/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the feature to retrieve. ### Response #### Success Response (200) - **feature** (object) - The feature object. ``` -------------------------------- ### Typical Resolver Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-resolvers.md Illustrates a standard resolver implementation for a resource type, including query methods for fetching all resources and a single resource by its index, as well as a field resolver for nested data. ```APIDOC ## ResourceResolver ### Description Provides query operations to fetch resources and their related fields. ### Operations #### `resources` Query Retrieves a list of all resources, supporting filtering by name and sorting. - **Type**: Query - **Returns**: `ResourceType[]` - **Arguments**: `ResourceArgs` (includes `name`, `order`, `skip`, `limit`) #### `resource` Query Retrieves a single resource by its unique index. - **Type**: Query - **Returns**: `ResourceType | null` - **Arguments**: `ResourceIndexArgs` (includes `index`) #### `relatedField` Field Resolver Resolves the nested `relatedField` for a given `ResourceType`. - **Type**: Field Resolver - **Root Type**: `ResourceType` - **Returns**: `RelatedType` ### Example Usage (Conceptual) ```graphql query GetResources($name: String, $order: OrderEnum) { resources(name: $name, order: $order) { index name # ... other fields } } query GetResourceByIndex($index: String!) { resource(index: $index) { index name relatedField { # ... fields of RelatedType } } } ``` ``` -------------------------------- ### Get Single Condition Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific condition by its index. ```APIDOC ## GET /api/2014/conditions/{index} ### Description Retrieves a specific condition by its index. ### Method GET ### Endpoint /api/2014/conditions/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the condition to retrieve. ### Response #### Success Response (200) - **condition** (object) - The condition object. ``` -------------------------------- ### Bundle OpenAPI Definition Source: https://github.com/5e-bits/5e-srd-api/blob/main/src/swagger/README.md Execute this npm command to bundle the OpenAPI definition and its references into a single JSON file located in `swagger/dist`. ```bash npm run bundle-swagger ``` -------------------------------- ### Testing Commands Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md npm scripts for executing unit and integration tests. Integration tests can be run locally using Docker. ```bash npm run test:unit # Unit tests npm run test:integration:local # Integration tests in Docker ``` -------------------------------- ### Get Single Alignment Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific alignment by its index. ```APIDOC ## GET /api/2014/alignments/{index} ### Description Retrieves a specific alignment by its index. ### Method GET ### Endpoint /api/2014/alignments/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the alignment to retrieve. ### Response #### Success Response (200) - **alignment** (object) - The alignment object. ``` -------------------------------- ### SimpleController - index Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Generic list implementation for standard resources. It validates parameters, checks cache, queries the database with specific fields, applies translations, caches the response, and returns a ResourceList. ```APIDOC ## GET /resource ### Description Retrieves a list of resources with standard sorting and field selection. ### Method GET ### Endpoint /resource ### Parameters #### Query Parameters - **index** (string) - Optional - Used for parameter format validation. ### Response #### Success Response (200) - **resourceList** (array) - Contains a list of resources, each with 'index', 'name', and 'url'. ### Response Example { "resourceList": [ { "index": "ability-scores", "name": "Ability Scores", "url": "/api/v2/ability-scores" } ] } ``` -------------------------------- ### Get Single Subrace Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific subrace by its index. ```APIDOC ## GET /api/2014/subraces/{index} ### Description Retrieves a specific subrace by its index. ### Method GET ### Endpoint /api/2014/subraces/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the subrace to retrieve. ### Response #### Success Response (200) - **subrace** (object) - The subrace object. ``` -------------------------------- ### Get Single Class Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific class by its index. ```APIDOC ## GET /api/2014/classes/{index} ### Description Retrieves a single class's complete details using its unique index. ### Method GET ### Endpoint /api/2014/classes/{index} #### Response ##### Success Response (200 OK) Returns a complete Class object including basic information, features, spellcasting details, and subclasses. ``` -------------------------------- ### Get Single Spell Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific spell by its index. ```APIDOC ## GET /api/2014/spells/{index} ### Description Retrieves a single spell's complete details using its unique index. ### Method GET ### Endpoint /api/2014/spells/{index} #### Response ##### Success Response (200 OK) Returns a complete Spell object including core details, components, effects, damage, saving throws, and related classes. ``` -------------------------------- ### Configure Rate Limiting Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/configuration.md Sets up a rate limiter using the 'rate-limit' package. Configuration values for window duration and maximum requests are read from environment variables. This limiter is applied to all incoming routes. ```typescript const limiter = rateLimit({ windowMs: rateLimitWindowMs, // From RATE_LIMIT_WINDOW_MS env var max: rateLimitMax, // From RATE_LIMIT_MAX env var message: `Rate limit of ${rateLimitMax} requests per ${rateLimitWindowMs / 1000} second(s) exceeded, try again later.` }) app.use(limiter) // Applied to all routes ``` -------------------------------- ### Run Unit Tests Source: https://github.com/5e-bits/5e-srd-api/blob/main/README.md Execute unit tests for the API. This command is run from the project's root directory. ```shell npm run test:unit ``` -------------------------------- ### Get Single Category Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific equipment category by its index. ```APIDOC ## GET /api/2014/equipment-categories/{index} ### Description Retrieves a specific equipment category by its index. ### Method GET ### Endpoint /api/2014/equipment-categories/{index} ### Response #### Success Response (200) - **index** (string) - The index of the category. - **name** (string) - The name of the category. - **equipment** (array) - A list of equipment items belonging to this category. ``` -------------------------------- ### Pagination (GraphQL) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Demonstrates how to paginate through results, specifying the number of items to skip and limit. ```APIDOC ## Query: spells (Pagination) ### Description Retrieves a paginated list of spells, allowing you to skip a certain number of results and limit the number returned. ### Usage ```graphql query { spells(skip: 20, limit: 10) { name } } ``` ``` -------------------------------- ### Get Single Monster (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves a specific monster by its index. ```APIDOC ## GET /api/2014/monsters/{index} ### Description Retrieves a specific monster by its index. ### Method GET ### Endpoint /api/2014/monsters/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The index of the monster to retrieve. ``` -------------------------------- ### Get All Monsters (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves a list of all monsters available in the API. ```APIDOC ## GET /api/2014/monsters ### Description Retrieves a list of all monsters. ### Method GET ### Endpoint /api/2014/monsters ``` -------------------------------- ### Get Spells by School (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Filter spells by their school of magic. ```bash curl "http://localhost:3000/api/2014/spells?school=evocation" ``` -------------------------------- ### Typical Controller Structure (index and show) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md This snippet demonstrates the common structure for REST controllers, including input validation with Zod, Redis caching, database querying, and translation application for both list and single resource endpoints. ```typescript // src/controllers/api/2014/{resource}Controller.ts import { NextFunction, Request, Response } from 'express' import { redisClient, ResourceList } from '@/util' import { applyTranslation } from '@/util/translation' export const index = async (req: Request, res: Response, next: NextFunction) => { try { // 1. Validate query parameters const validatedQuery = SchemaType.safeParse(req.query) if (!validatedQuery.success) { return res.status(400).json({ error: '...', details: validatedQuery.error.issues }) } // 2. Check cache const cached = await redisClient.get(req.originalUrl) if (cached !== null) { return res.status(200).json(JSON.parse(cached)) } // 3. Query database const data = await Model.find(searchQueries).select(...).sort(...) // 4. Apply translations const { docs: translated, wasTranslated } = await applyTranslationToList(data, 'namespace', lang) // 5. Format and cache response const jsonData = ResourceList(translated) await redisClient.set(req.originalUrl, JSON.stringify(jsonData)) res.setHeader('Content-Language', wasTranslated ? lang : 'en') return res.status(200).json(jsonData) } catch (err) { next(err) } } export const show = async (req: Request, res: Response, next: NextFunction) => { try { // Similar pattern for single resource const validatedParams = ShowParamsSchema.safeParse(req.params) if (!validatedParams.success) { return res.status(400).json({ error: '...', details: validatedParams.error.issues }) } const { index } = validatedParams.data const data = await Model.findOne({ index }) if (!data) return next() // 404 const translated = await applyTranslation(data.toObject(), 'namespace', lang) res.setHeader('Content-Language', translated !== plain ? lang : 'en') return res.status(200).json(translated) } catch (err) { next(err) } } ``` -------------------------------- ### Subclass Controller - show Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Provides the standard list/show pattern for subclasses, inheriting from SimpleController. ```APIDOC ## GET /subclasses/{index} ### Description Retrieves a single subclass by its index. ### Method GET ### Endpoint /subclasses/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The index of the subclass to retrieve. ### Response #### Success Response (200) - **subclass** (object) - The full object of the requested subclass. ### Response Example { "index": "battle-master", "name": "Battle Master", "subclass_levels": "/api/v2/subclasses/battle-master/levels", "class": { "name": "Fighter", "url": "/api/v2/classes/fighter" }, "url": "/api/v2/subclasses/battle-master" } ``` -------------------------------- ### Get Specific Class Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Retrieves detailed information for a single class by its index. ```APIDOC ## GET /api/2014/classes/{index} ### Description Retrieves a single class by index. ### Method GET ### Endpoint /api/2014/classes/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The index of the class to retrieve. ### Response #### Success Response (200) - Complete Class object ``` -------------------------------- ### Get Single Weapon Property Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific weapon property by its index. ```APIDOC ## GET /api/2014/weapon-properties/{index} ### Description Retrieves a specific weapon property by its index. ### Method GET ### Endpoint /api/2014/weapon-properties/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the weapon property to retrieve. ### Response #### Success Response (200) - **weapon-property** (object) - The weapon property object. ``` -------------------------------- ### Clone 5e-database Repository Source: https://github.com/5e-bits/5e-srd-api/blob/main/README.md Clone the 5e-database repository to build a custom image for M1/M2/M3 Macs or for local development. ```shell cd ../ git clone https://github.com/5e-bits/5e-database.git ``` -------------------------------- ### Get Single Rule Section Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific rule section by its index. ```APIDOC ## GET /api/2014/rule-sections/{index} ### Description Retrieves a specific rule section by its index. ### Method GET ### Endpoint /api/2014/rule-sections/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the rule section to retrieve. ### Response #### Success Response (200) - **rule-section** (object) - The rule section object. ``` -------------------------------- ### Configure MongoDB Connection URI Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/configuration.md Set the MONGODB_URI for production and TEST_MONGODB_URI for testing. The test environment falls back to MONGODB_URI if TEST_MONGODB_URI is not set. ```bash MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/5e-database TEST_MONGODB_URI=mongodb://localhost:27017/5e-database-test ``` -------------------------------- ### Configure AWS S3 Connection Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/configuration.md Set AWS_REGION, AWS_CONFIG_ENV, AWS_ACCESS_KEY_ID, and AWS_SECRET_ACCESS_KEY for S3 image storage. Use 'localstack_dev' for local testing with LocalStack. ```bash AWS_REGION=us-west-1 AWS_CONFIG_ENV=prod AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ``` ```bash AWS_CONFIG_ENV=localstack_dev AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test ``` -------------------------------- ### Get Single Magic School Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific magic school by its index. ```APIDOC ## GET /api/2014/magic-schools/{index} ### Description Retrieves a specific magic school by its index. ### Method GET ### Endpoint /api/2014/magic-schools/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the magic school to retrieve. ### Response #### Success Response (200) - **magic-school** (object) - The magic school object. ``` -------------------------------- ### Get Single Magic Item Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific magic item by its index. ```APIDOC ## GET /api/2014/magic-items/{index} ### Description Retrieves a specific magic item by its index. ### Method GET ### Endpoint /api/2014/magic-items/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the magic item to retrieve. ### Response #### Success Response (200) - **magic-item** (object) - The magic item object. ``` -------------------------------- ### REST Controllers Structure Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/INDEX.md Illustrates the directory structure for REST controllers, separating API versions and generic handlers. ```tree src/controllers/ ├── api/ │ ├── 2014/ │ │ ├── monsterController.ts │ │ ├── spellController.ts │ │ ├── classController.ts │ │ └── ... (20+ more) │ └── 2024/ │ └── ... (2024 edition variants) └── simpleController.ts (generic handler) ``` -------------------------------- ### Get Single Damage Type Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific damage type by its index. ```APIDOC ## GET /api/2014/damage-types/{index} ### Description Retrieves a specific damage type by its index. ### Method GET ### Endpoint /api/2014/damage-types/{index} ### Parameters #### Path Parameters - **index** (string) - Required - The unique index of the damage type to retrieve. ### Response #### Success Response (200) - **damage-type** (object) - The damage type object. ``` -------------------------------- ### Get Single Ability Score Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a specific ability score by its index. ```APIDOC ## GET /api/2014/ability-scores/{index} ### Description Retrieves a specific ability score by its index. ### Method GET ### Endpoint /api/2014/ability-scores/{index} ### Parameters #### Path Parameters - **index** (string) - Required - Ability index: `str`, `dex`, `con`, `int`, `wis`, `cha` ### Response #### Success Response (200) - **index** (string) - The index of the ability score. - **name** (string) - The name of the ability score. - **full_name** (string) - The full name of the ability score. - **description** (string) - A description of the ability score. - **skills** (array) - A list of skills associated with this ability score. ``` -------------------------------- ### SimpleController Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/middleware-utilities.md A generic REST controller for resources that follow the standard list/show pattern. It handles common operations like indexing and showing resources, along with caching, translation, and validation. ```APIDOC ## SimpleController ### Description Generic REST controller for resources that follow the standard list/show pattern. ### Constructor ```typescript constructor(model: Model) ``` ### Methods - `index(req: Request, res: Response, next: NextFunction): void` - `show(req: Request, res: Response, next: NextFunction): void` ### Usage ```typescript const simpleController = new SimpleController(MonsterModel) export const index = (req, res, next) => simpleController.index(req, res, next) export const show = (req, res, next) => simpleController.show(req, res, next) ``` ### Pattern - `index`: Returns list of resources with count and results - `show`: Returns single resource by index - Handles caching, translation, validation automatically ``` -------------------------------- ### Get Spells in Spanish (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves a list of spells, with results in Spanish. ```APIDOC ## GET /api/2014/spells?lang=es ### Description Retrieves spells with results in Spanish. ### Method GET ### Endpoint /api/2014/spells ### Query Parameters - **lang** (string) - Optional - Set to 'es' to get results in Spanish. ``` -------------------------------- ### Configure Rate Limiting Parameters Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/configuration.md Adjust RATE_LIMIT_WINDOW_MS for the time window in milliseconds and RATE_LIMIT_MAX for the maximum requests allowed within that window. ```bash RATE_LIMIT_WINDOW_MS=5000 # 5 seconds RATE_LIMIT_MAX=100 # 100 requests per 5 seconds ``` -------------------------------- ### List All Classes Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Retrieves a list of all available classes. ```APIDOC ## GET /api/2014/classes ### Description Lists all classes. ### Method GET ### Endpoint /api/2014/classes ### Response #### Success Response (200) - Array of Class objects via SimpleController ``` -------------------------------- ### Get Class Levels (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves all level information for a specific class. ```APIDOC ## GET /api/2014/classes/{class}/levels ### Description Retrieves all level information for a specific class. ### Method GET ### Endpoint /api/2014/classes/{class}/levels ### Parameters #### Path Parameters - **class** (string) - Required - The class for which to retrieve level information. ``` -------------------------------- ### Get Spells by Level (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves a list of spells filtered by their level. ```APIDOC ## GET /api/2014/spells?level=... ### Description Retrieves spells filtered by level. ### Method GET ### Endpoint /api/2014/spells ### Query Parameters - **level** (string) - Optional - Comma-separated list of spell levels to filter by. ``` -------------------------------- ### MongoDB Connection String Formats Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Reference for constructing MongoDB connection strings for both standard and SRV deployments. Includes default database names for production and testing. ```plaintext mongodb://[user:password]@[host]:[port]/[database] mongodb+srv://[user:password]@[cluster].mongodb.net/[database] ``` -------------------------------- ### Get Spells in Spanish (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieve spell data localized in Spanish. ```bash curl "http://localhost:3000/api/2014/spells?lang=es" ``` -------------------------------- ### List Backgrounds Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/rest-endpoints.md Retrieves a list of all backgrounds. ```APIDOC ## GET /api/2014/backgrounds ### Description Retrieves a list of all backgrounds. ### Method GET ### Endpoint /api/2014/backgrounds ### Response #### Success Response (200) - **backgrounds** (array) - An array of background objects. ``` -------------------------------- ### Get Class Levels (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieve all available levels for a specific class. ```bash curl http://localhost:3000/api/2014/classes/wizard/levels ``` -------------------------------- ### Controller Pattern Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Demonstrates the typical structure of a REST controller, including input validation, cache checking, database querying, translation, and response formatting. ```APIDOC ## Controller Pattern **Typical Controller Structure:** ```typescript // src/controllers/api/2014/{resource}Controller.ts import { NextFunction, Request, Response } from 'express' import { redisClient, ResourceList } from '@/util' import { applyTranslation } from '@/util/translation' export const index = async (req: Request, res: Response, next: NextFunction) => { try { // 1. Validate query parameters const validatedQuery = SchemaType.safeParse(req.query) if (!validatedQuery.success) { return res.status(400).json({ error: '...', details: validatedQuery.error.issues }) } // 2. Check cache const cached = await redisClient.get(req.originalUrl) if (cached !== null) { return res.status(200).json(JSON.parse(cached)) } // 3. Query database const data = await Model.find(searchQueries).select(...).sort(...) // 4. Apply translations const { docs: translated, wasTranslated } = await applyTranslationToList(data, 'namespace', lang) // 5. Format and cache response const jsonData = ResourceList(translated) await redisClient.set(req.originalUrl, JSON.stringify(jsonData)) res.setHeader('Content-Language', wasTranslated ? lang : 'en') return res.status(200).json(jsonData) } catch (err) { next(err) } } export const show = async (req: Request, res: Response, next: NextFunction) => { try { // Similar pattern for single resource const validatedParams = ShowParamsSchema.safeParse(req.params) if (!validatedParams.success) { return res.status(400).json({ error: '...', details: validatedParams.error.issues }) } const { index } = validatedParams.data const data = await Model.findOne({ index }) if (!data) return next() // 404 const translated = await applyTranslation(data.toObject(), 'namespace', lang) res.setHeader('Content-Language', translated !== plain ? lang : 'en') return res.status(200).json(translated) } catch (err) { next(err) } } ``` ``` -------------------------------- ### Get Single Monster (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieve details for a specific monster by its index. ```bash curl http://localhost:3000/api/2014/monsters/aboleth ``` -------------------------------- ### Equipment Resolver Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/graphql-resolvers.md Queries for equipment items, including their cost and properties. ```APIDOC ## Equipment Resolver ### Queries - `equipment(name?, order?, skip?, limit?)` → `[Equipment]` - `equipmentItem(index!)` → `Equipment | null` ### Sort Fields - NAME - WEIGHT ### Example ```graphql query { equipment(name: "Sword") { index name cost { quantity unit } weight damage { damageDice damageType { name } } } } ``` ``` -------------------------------- ### Get Ability Scores (GraphQL) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves a list of ability scores with their associated skills. ```APIDOC ## Query: abilityScores ### Description Retrieves a list of ability scores, including their index, name, full name, and associated skills. ### Usage ```graphql query { abilityScores { index name fullName skills { name } } } ``` ``` -------------------------------- ### Pagination (GraphQL) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Implement pagination for spell queries by specifying skip and limit parameters. ```graphql query { spells(skip: 20, limit: 10) { name } } ``` -------------------------------- ### Get Specific Class Level (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves information for a specific level of a class. ```APIDOC ## GET /api/2014/classes/{class}/levels/{level} ### Description Retrieves information for a specific level of a class. ### Method GET ### Endpoint /api/2014/classes/{class}/levels/{level} ### Parameters #### Path Parameters - **class** (string) - Required - The class for which to retrieve level information. - **level** (integer) - Required - The specific level to retrieve. ``` -------------------------------- ### Subclass Controller - index Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Provides the standard list/show pattern for subclasses, inheriting from SimpleController. ```APIDOC ## GET /subclasses ### Description Retrieves a list of subclasses. ### Method GET ### Endpoint /subclasses ### Response #### Success Response (200) - **subclassList** (array) - Contains a list of subclasses. ### Response Example { "subclassList": [ { "index": "battle-master", "name": "Battle Master", "url": "/api/v2/subclasses/battle-master" } ] } ``` -------------------------------- ### Get Spells by School (REST) Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/quick-reference.md Retrieves a list of spells filtered by their school of magic. ```APIDOC ## GET /api/2014/spells?school=... ### Description Retrieves spells filtered by school of magic. ### Method GET ### Endpoint /api/2014/spells ### Query Parameters - **school** (string) - Optional - The school of magic to filter by. ``` -------------------------------- ### Monster Show Database Query Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/api-reference/controllers.md Example of a database query to find a single monster by its index. ```typescript const data = await Monster.findOne({ index: index }) ``` -------------------------------- ### Apollo Server Middleware Source: https://github.com/5e-bits/5e-srd-api/blob/main/_autodocs/middleware-utilities.md Creates and configures an Apollo Server instance for handling GraphQL requests. It returns a configured ApolloServer instance ready for integration with an Express application. ```APIDOC ## Apollo Server Middleware ### Description Creates and configures an Apollo Server instance for the GraphQL endpoint. This middleware is essential for setting up the GraphQL API. ### Function Signature ```typescript async function createApolloMiddleware( schema: GraphQLSchema ): Promise ``` ### Returns Returns a configured `ApolloServer` instance ready for `.start()` and integration with an Express application. ### Usage ```typescript const apollo = await createApolloMiddleware(schema) await apollo.start() app.use( '/graphql/2014', expressMiddleware(apollo, { context: async ({ req }) => ({ token: req.headers.token, lang: req.lang }) }) ) ``` ```