### Setup and Installation Commands Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Shell commands to clone the repository, install dependencies, configure environment variables, and start the development server. ```bash # Clone the repository git clone https://github.com/your-username/vedic-shastra-api.git cd vedic-shastra-api # Install dependencies npm install # Create environment file cat > .env << EOF PORT=5000 MONGODB_URI=mongodb://localhost/vedicshastra JWT_SECRET=your-super-secret-jwt-key NODE_ENV=development EOF # Seed the database (optional) ts-node seed/categories.ts ts-node seed/scriptures.ts # Start the development server npm run dev # Server running at http://localhost:5000 # Swagger docs at http://localhost:5000/api-docs ``` -------------------------------- ### Install Dependencies Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Commands to clone the repository and install required packages. ```bash git clone https://github.com/your-username/vedic-shastra-api.git cd vedic-shastra-api npm install ``` -------------------------------- ### Start Development Server Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Command to launch the API in development mode. ```bash npm run dev ``` -------------------------------- ### Retrieve All Scriptures Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Example request to fetch all available scriptures. ```bash curl http://localhost:5000/api/scriptures ``` -------------------------------- ### Search Scriptures by Keyword Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Example request to filter scriptures using a search term. ```bash curl http://localhost:5000/api/scriptures?search=Agni ``` -------------------------------- ### Swagger Documentation Setup Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Configures Swagger UI for interactive API documentation. Accessible at the '/api-docs' endpoint. Requires 'swagger-jsdoc' and 'swagger-ui-express'. ```typescript import swaggerJsDoc from 'swagger-jsdoc'; import swaggerUi from 'swagger-ui-express'; import { Application } from 'express'; const swaggerOptions = { definition: { openapi: '3.0.0', info: { title: 'Vedic Shastra API', version: '1.0.0', description: 'API Documentation for Vedic Shastra' } }, apis: ['./routes/*.ts'] }; const swaggerDocs = swaggerJsDoc(swaggerOptions); export const setupSwagger = (app: Application) => { app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs)); }; ``` -------------------------------- ### Retrieve Scriptures by Category Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Example request to filter scriptures by a specific category. ```bash curl http://localhost:5000/api/scriptures?category=Vedas ``` -------------------------------- ### GET /api/categories Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Retrieve a list of all available scripture categories. ```APIDOC ## GET /api/categories ### Description Retrieve all scripture categories (e.g., Vedas, Upanishads). ### Method GET ### Endpoint /api/categories ``` -------------------------------- ### Environment Variables Configuration Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Example configuration for environment variables in a .env file. These variables control application settings like port, database URI, and JWT secret. ```bash # .env file configuration PORT=5000 MONGODB_URI=mongodb://localhost/vedicshastra JWT_SECRET=your-super-secret-jwt-key NODE_ENV=development ``` -------------------------------- ### Define Error Response JSON Structures Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Example JSON payloads for 404 and 500 error responses. ```json // 404 Not Found { "message": "Not Found - /api/invalid-route", "stack": "Error: Not Found - /api/invalid-route\n at notFound..." } // 500 Server Error { "message": "Server error", "stack": null // Hidden in production } ``` -------------------------------- ### GET /api/scriptures Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Retrieve a list of all scriptures, with optional filtering by category, verse, or search term. ```APIDOC ## GET /api/scriptures ### Description Get all scriptures or filter by category, verse, or search term. ### Method GET ### Endpoint /api/scriptures ### Parameters #### Query Parameters - **search** (string) - Optional - Search term to filter scriptures - **category** (string) - Optional - Category name to filter scriptures ``` -------------------------------- ### Get All Scriptures Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Retrieves all scriptures from the database. This is a public endpoint that returns an array of scripture documents including their title, content, category, verse reference, and date added. ```APIDOC ## GET /api/scriptures ### Description Retrieves all scriptures from the database. This is a public endpoint that returns an array of scripture documents including their title, content, category, verse reference, and date added. ### Method GET ### Endpoint /api/scriptures ### Response #### Success Response (200) - **_id** (string) - Unique identifier for the scripture. - **title** (string) - The title of the scripture entry. - **content** (string) - The textual content of the scripture verse. - **category** (string) - The category of the scripture (e.g., Veda, Upanishad, Puran, Bhagavad Gita). - **verse** (string) - The specific verse reference. - **dateAdded** (string) - The date and time when the scripture was added. #### Response Example ```json [ { "_id": "507f1f77bcf86cd799439011", "title": "Rig Veda Mandala 1 Hymn 1", "content": "अग्निमीळे पुरोहितं यज्ञस्य देवं ऋत्विजम् | होतारं रत्नधातमम् ||", "category": "Veda", "verse": "1.1.1", "dateAdded": "2024-01-15T10:30:00.000Z" }, { "_id": "507f1f77bcf86cd799439012", "title": "Bhagavad Gita Chapter 2 Verse 47", "content": "कर्मण्येवाधिकारस्ते मा फलेषु कदाचन | मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि ||", "category": "Bhagavad Gita", "verse": "2.47", "dateAdded": "2024-01-15T11:00:00.000Z" } ] ``` ``` -------------------------------- ### GET /api/translations/:scriptureId Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Retrieve all available translations for a specific scripture. ```APIDOC ## GET /api/translations/:scriptureId ### Description Retrieve all translations for a specific scripture. ### Method GET ### Endpoint /api/translations/:scriptureId ### Parameters #### Path Parameters - **scriptureId** (string) - Required - The ID of the scripture to fetch translations for ``` -------------------------------- ### GET /api/scriptures/:id Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Retrieve details for a specific scripture using its unique identifier. ```APIDOC ## GET /api/scriptures/:id ### Description Get a specific scripture by ID. ### Method GET ### Endpoint /api/scriptures/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the scripture ``` -------------------------------- ### Seed Database Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Commands to populate the database with initial data. ```bash ts-node seed/categories.ts ts-node seed/scriptures.ts ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Required configuration for the .env file. ```env PORT=5000 MONGODB_URI=mongodb://localhost/vedicshastra # Or your MongoDB connection string ``` -------------------------------- ### Project Directory Structure Source: https://github.com/bugsum/vedic-shastra-api/blob/main/README.md Overview of the project file organization. ```text vedic-shastra-api/ │ ├── src/ │ ├── controllers/ # API controllers │ ├── models/ # Mongoose models for scriptures, categories, translations │ ├── routes/ # API routes │ ├── seed/ # Data seeding scripts │ ├── validations/ # Input validation with Joi │ └── app.ts # Main application entry point │ ├── tests/ # Unit tests ├── .env # Environment variables ├── package.json # Project dependencies └── README.md # Project documentation ``` -------------------------------- ### Database Connection Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Establishes a connection to MongoDB using Mongoose. Includes error handling and process exit on failure. Ensure MONGO_URI is set in environment variables. ```typescript import mongoose from 'mongoose'; const connectDB = async () => { try { const conn = await mongoose.connect(process.env.MONGO_URI || '', {}); console.log(`MongoDB Connected: ${conn.connection.host}`); } catch (error) { if (error instanceof Error) { console.error(`Error: ${error.message}`); } else { console.error('An unknown error occurred'); } process.exit(1); } }; export default connectDB; ``` -------------------------------- ### Retrieve All Scriptures via cURL Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Fetches the full list of scripture documents from the public API endpoint. ```bash # Retrieve all scriptures curl -X GET http://localhost:5000/api/scriptures # Expected Response (200 OK) [ { "_id": "507f1f77bcf86cd799439011", "title": "Rig Veda Mandala 1 Hymn 1", "content": "अग्निमीळे पुरोहितं यज्ञस्य देवं ऋत्विजम् | होतारं रत्नधातमम् ||", "category": "Veda", "verse": "1.1.1", "dateAdded": "2024-01-15T10:30:00.000Z" }, { "_id": "507f1f77bcf86cd799439012", "title": "Bhagavad Gita Chapter 2 Verse 47", "content": "कर्मण्येवाधिकारस्ते मा फलेषु कदाचन | मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि ||", "category": "Bhagavad Gita", "verse": "2.47", "dateAdded": "2024-01-15T11:00:00.000Z" } ] ``` -------------------------------- ### Create New Scripture via cURL Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Adds a new scripture entry to the database. Requires a valid JWT Bearer token in the Authorization header. ```bash # Add a new scripture (requires authentication) curl -X POST http://localhost:5000/api/scriptures \ -H "Content-Type: application/json" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -d '{ "title": "Isha Upanishad Verse 1", "content": "ईशावास्यमिदं सर्वं यत्किञ्च जगत्यां जगत् | तेन त्यक्तेन भुञ्जीथा मा गृधः कस्यस्विद्धनम् ||", "category": "Upanishad", "verse": "1" }' # Expected Response (201 Created) { "_id": "507f1f77bcf86cd799439013", "title": "Isha Upanishad Verse 1", "content": "ईशावास्यमिदं सर्वं यत्किञ्च जगत्यां जगत् | तेन त्यक्तेन भुञ्जीथा मा गृधः कस्यस्विद्धनम् ||", "category": "Upanishad", "verse": "1", "dateAdded": "2024-01-15T12:00:00.000Z" } # Error Response - Missing Token (401 Unauthorized) { "message": "Not authorized, no token" } # Error Response - Invalid Token (401 Unauthorized) { "message": "Not authorized, token failed" } # Error Response - Validation Failed (400 Bad Request) { "message": "\"category\" must be one of [Veda, Upanishad, Puran, Bhagavad Gita]" } ``` -------------------------------- ### Logger Configuration Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Configures Winston logger for console and file-based logging. Logs errors to 'error.log' and all logs to 'combined.log'. ```typescript import { createLogger, format, transports } from 'winston'; const logger = createLogger({ format: format.combine( format.timestamp(), format.json() ), transports: [ new transports.Console(), new transports.File({ filename: 'error.log', level: 'error' }), new transports.File({ filename: 'combined.log' }) ] }); export default logger; ``` -------------------------------- ### Implement Error Middleware in TypeScript Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Global error handling middleware for Express applications, including a 404 handler and a centralized error response formatter. ```typescript import { Request, Response, NextFunction } from 'express'; import logger from '../utils/logger'; // Handle 404 Not Found errors export const notFound = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Not Found - ${req.originalUrl}`); res.status(404); next(error); }; // Global error handler export const errorHandler = (err: any, req: Request, res: Response, next: NextFunction) => { logger.error(err.message); const statusCode = res.statusCode === 200 ? 500 : res.statusCode; res.status(statusCode).json({ message: err.message, stack: process.env.NODE_ENV === 'production' ? null : err.stack }); }; ``` -------------------------------- ### Authentication Middleware Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Protects routes by verifying JWT tokens. It extracts the user from the database and attaches it to the request object. Requires 'jsonwebtoken' and Mongoose User model. ```typescript import jwt from 'jsonwebtoken'; import { Request, Response, NextFunction } from 'express'; import User, { IUser } from '../models/User'; interface AuthRequest extends Request { user?: IUser; } export const protect = async (req: AuthRequest, res: Response, next: NextFunction) => { let token; if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { try { token = req.headers.authorization.split(' ')[1]; const decoded = jwt.verify(token, process.env.JWT_SECRET || 'secret') as { id: string }; req.user = await User.findById(decoded.id).select('-password'); next(); } catch (error) { res.status(401).json({ message: 'Not authorized, token failed' }); } } if (!token) { res.status(401).json({ message: 'Not authorized, no token' }); } }; ``` -------------------------------- ### Add New Scripture Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Creates a new scripture entry in the database. This endpoint requires JWT authentication via Bearer token. The request body must include title, content, and category. The verse field is optional. ```APIDOC ## POST /api/scriptures ### Description Creates a new scripture entry in the database. This endpoint requires JWT authentication via Bearer token. The request body must include title, content, and category (must be one of: Veda, Upanishad, Puran, Bhagavad Gita). The verse field is optional. ### Method POST ### Endpoint /api/scriptures ### Parameters #### Request Body - **title** (string) - Required - The title of the scripture entry. - **content** (string) - Required - The textual content of the scripture verse. - **category** (string) - Required - The category of the scripture. Must be one of: Veda, Upanishad, Puran, Bhagavad Gita. - **verse** (string) - Optional - The specific verse reference. ### Request Example ```json { "title": "Isha Upanishad Verse 1", "content": "ईशावास्यमिदं सर्वं यत्किञ्च जगत्यां जगत् | तेन त्यक्तेन भुञ्जीथा मा गृधः कस्यस्विद्धनम् ||", "category": "Upanishad", "verse": "1" } ``` ### Response #### Success Response (201 Created) - **_id** (string) - Unique identifier for the newly created scripture. - **title** (string) - The title of the scripture entry. - **content** (string) - The textual content of the scripture verse. - **category** (string) - The category of the scripture. - **verse** (string) - The specific verse reference. - **dateAdded** (string) - The date and time when the scripture was added. #### Response Example ```json { "_id": "507f1f77bcf86cd799439013", "title": "Isha Upanishad Verse 1", "content": "ईशावास्यमिदं सर्वं यत्किञ्च जगत्यां जगत् | तेन त्यक्तेन भुञ्जीथा मा गृधः कस्यस्विद्धनम् ||", "category": "Upanishad", "verse": "1", "dateAdded": "2024-01-15T12:00:00.000Z" } ``` #### Error Responses - **401 Unauthorized** - Missing or invalid JWT token. - **400 Bad Request** - Validation failed for request body fields. ``` -------------------------------- ### Define Scripture Mongoose Model Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Defines the schema and interface for scripture documents, enforcing specific categories. ```typescript import { Schema, model, Document } from 'mongoose'; // Scripture interface definition interface IScripture extends Document { title: string; content: string; category: 'Veda' | 'Upanishad' | 'Puran' | 'Bhagavad Gita'; verse?: string; dateAdded: Date; } // Mongoose schema const scriptureSchema: Schema = new Schema({ title: { type: String, required: true }, content: { type: String, required: true }, category: { type: String, enum: ['Veda', 'Upanishad', 'Puran', 'Bhagavad Gita'], required: true }, verse: { type: String }, dateAdded: { type: Date, default: Date.now } }); const Scripture = model('Scripture', scriptureSchema); export default Scripture; ``` -------------------------------- ### Generate JWT Token Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Generates a JWT token for user authentication with a 30-day expiration. Ensure JWT_SECRET is set in environment variables. ```typescript import jwt from 'jsonwebtoken'; // Generate JWT token for user authentication export const generateToken = (userId: string): string => { return jwt.sign({ id: userId }, process.env.JWT_SECRET || 'secret', { expiresIn: '30d' }); }; // Usage example const token = generateToken('507f1f77bcf86cd799439011'); // Returns: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Define User Mongoose Model Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Defines the user schema with password hashing and a comparison method for authentication. ```typescript import { Schema, model, Document } from 'mongoose'; import bcrypt from 'bcryptjs'; interface IUser extends Document { username: string; password: string; comparePassword(password: string): Promise; } const userSchema = new Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true } }); // Password comparison method for authentication userSchema.methods.comparePassword = async function (password: string): Promise { return await bcrypt.compare(password, this.password); }; const User = model('User', userSchema); export default User; ``` -------------------------------- ### Scripture Validation Schema Source: https://context7.com/bugsum/vedic-shastra-api/llms.txt Validates scripture data using Joi, ensuring required fields are present and category values are restricted to valid scripture types. Use this schema to validate request bodies. ```typescript import Joi from 'joi'; // Validation schema for scripture creation/updates export const scriptureValidationSchema = Joi.object({ title: Joi.string().required(), content: Joi.string().required(), category: Joi.string().valid('Veda', 'Upanishad', 'Puran', 'Bhagavad Gita').required(), verse: Joi.string().optional() }); // Usage in controller const { error } = scriptureValidationSchema.validate(req.body); if (error) { res.status(400).json({ message: error.details[0].message }); return; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.