### Environment File Setup (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Commands to copy the example environment file and instructions on how to update it. ```bash cp .env.example .env ``` -------------------------------- ### Install Dependencies (npm) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Install Dependencies (yarn) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to install project dependencies using yarn. ```bash yarn install ``` -------------------------------- ### Start Development Server (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to start the development server. ```bash npm run dev ``` -------------------------------- ### Example .env Configuration (env) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md An example of the .env file content, showing configuration for database, API, authentication, external services, and feature flags. ```env # Database Configuration DATABASE_URL=postgresql://username:password@localhost:5432/context7_test # API Configuration API_PORT=3000 API_HOST=localhost # Authentication JWT_SECRET=your-super-secret-jwt-key SESSION_SECRET=your-session-secret # External Services REDIS_URL=redis://localhost:6379 MONGODB_URL=mongodb://localhost:27017/context7 # Feature Flags ENABLE_ANALYTICS=true ENABLE_DEBUG_MODE=false ``` -------------------------------- ### Verify Installations (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Commands to check if Node.js, npm, Git, and Docker are installed and their versions. ```bash node --version npm --version git --version docker --version ``` -------------------------------- ### Start PostgreSQL (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Commands to start the PostgreSQL service, depending on the operating system (macOS with Homebrew or Linux systemd). ```bash brew services start postgresql # or sudo systemctl start postgresql ``` -------------------------------- ### Setup Development Environment with npm Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md Initializes a new Node.js project and installs core Context7 dependencies and development tools. ```bash mkdir my-context7-app cd my-context7-app npm init -y npm install @context7/core @context7/auth @context7/ui npm install --save-dev @context7/dev-tools typescript @types/node ``` -------------------------------- ### Database Migration (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to run database migrations using npm. ```bash npm run db:migrate ``` -------------------------------- ### Run Test Suite (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to execute the entire test suite using npm. ```bash npm test ``` -------------------------------- ### Start Docker Compose Services (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to start all services defined in the docker-compose.yml file in detached mode. ```bash docker-compose up -d ``` -------------------------------- ### Clone Repository and Navigate (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Steps to clone the Context7-Test repository from GitHub and change the directory into the project folder. ```bash git clone https://github.com/MWGMorningwood/Context7-Test.git cd Context7-Test ``` -------------------------------- ### Database Seeding (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to seed the database with sample data using npm. ```bash npm run db:seed ``` -------------------------------- ### Stage and Commit Changes (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Git commands to stage all changes and commit them with a descriptive message. ```bash git add . git commit -m "Add: implement user authentication" ``` -------------------------------- ### Create Feature Branch (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Git command to create a new branch for feature development, starting from the 'main' branch. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Install Context7 Go SDK Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/api-reference.md Command to fetch the official Context7 SDK for Go using the go get command. ```bash go get github.com/context7/go-sdk ``` -------------------------------- ### Build Development Docker Image (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to build a Docker image using a specific Dockerfile (docker/Dockerfile.dev) and tag it. ```bash docker build -f docker/Dockerfile.dev -t context7-dev . ``` -------------------------------- ### Run Specific Tests (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to run specific tests by filtering based on a pattern, using npm. ```bash npm test -- --grep "user service" ``` -------------------------------- ### Reinstall Dependencies (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Commands to remove the node_modules folder and package-lock.json file, then reinstall dependencies to resolve potential issues. ```bash rm -rf node_modules package-lock.json npm install ``` -------------------------------- ### View Docker Logs (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to follow the logs of a specific service (e.g., 'app') in real-time. ```bash docker-compose logs -f app ``` -------------------------------- ### Format Code (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to format code using npm, likely invoking Prettier. ```bash npm run format ``` -------------------------------- ### Run Development Container (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to run a Docker container from the 'context7-dev' image, mounting the current directory, mapping ports, and executing the development server. ```bash docker run -it --rm \ -v $(pwd):/app \ -p 3000:3000 \ context7-dev npm run dev ``` -------------------------------- ### Lint Code (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to check code for linting issues using npm. ```bash npm run lint ``` -------------------------------- ### Start Development Server and Run Tests (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md Commands to start the development server and run tests for the project. ```bash npm run dev npm test ``` -------------------------------- ### Run Tests in Watch Mode (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to run tests continuously, re-running them when files change. ```bash npm run test:watch ``` -------------------------------- ### Install Context7 Node.js SDK Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/api-reference.md Command to install the official Context7 SDK for JavaScript and Node.js using npm. ```bash npm install context7-sdk ``` -------------------------------- ### Fix Linting Issues (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to automatically fix linting issues using npm. ```bash npm run lint:fix ``` -------------------------------- ### Install Context7 Python SDK Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/api-reference.md Command to install the official Context7 SDK for Python using pip. ```bash pip install context7-sdk ``` -------------------------------- ### Push Branch and Create Pull Request (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Git commands to push the local feature branch to the remote repository and initiate a pull request. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Kill Process on Port (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to find and kill any process currently using a specific port (e.g., 3000). ```bash lsof -ti:3000 | xargs kill -9 ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md These bash commands are used to build a Docker image from the Dockerfile and run a container from that image. The first command tags the image as 'my-context7-app', and the second command starts a container, mapping port 80 of the container to port 80 on the host machine. ```bash docker build -t my-context7-app . docker run -p 80:80 my-context7-app ``` -------------------------------- ### Clone Repository and Install Dependencies (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md Commands to clone the project repository and install its dependencies using npm. ```bash git clone https://github.com/your-username/Context7-Test.git cd Context7-Test npm install ``` -------------------------------- ### Stop Docker Compose Services (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/getting-started.md Command to stop and remove containers, networks, and volumes defined in the docker-compose.yml file. ```bash docker-compose down ``` -------------------------------- ### JavaScript Arrow Functions Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/javascript-basics.md Explains and shows examples of arrow functions, a concise syntax for writing function expressions in JavaScript. Covers simple arrow functions, those with block bodies, and single-parameter syntax. ```javascript // Simple arrow function const multiply = (a, b) => a * b; // Arrow function with block body const processData = (data) => { const processed = data.map(x => x * 2); return processed.filter(x => x > 10); }; // Single parameter (parentheses optional) const square = x => x * x; console.log(multiply(4, 5)); // 20 console.log(square(6)); // 36 ``` -------------------------------- ### TypeScript Interface and Function Example Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md Demonstrates defining a TypeScript interface for user data and a function to create a user, contrasting good practice with avoiding 'any' types. ```typescript // Good interface User { id: string; name: string; email: string; } function createUser(userData: Omit): User { return { id: generateId(), ...userData }; } // Avoid function createUser(userData: any): any { return { id: generateId(), ...userData }; } ``` -------------------------------- ### Demonstrate React Grid Component Usage Source: https://github.com/mwgmorningwood/context7-test/blob/docs/examples/react-components.md This example showcases how to use the Grid component within a React application. It demonstrates creating a responsive layout with a container and grid items, controlling spacing and breakpoints. The example also includes integrating other common UI elements like a Button, a Table with custom rendering for a 'Role' column, and a Modal, illustrating modern React patterns. ```jsx function App() { const [modalOpen, setModalOpen] = useState(false); const [tableData] = useState([ { id: 1, name: 'John Doe', email: 'john@example.com', role: 'Admin' }, { id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'User' } ]); const columns = [ { key: 'name', title: 'Name' }, { key: 'email', title: 'Email' }, { key: 'role', title: 'Role', render: (value) => ( {value} ) } ]; return (

Component Examples

console.log('Selected:', selected)} /> setModalOpen(false)} title="Example Modal" >

This is an example modal with accessibility features.

); } ``` -------------------------------- ### JavaScript Function Parameters: Default and Rest Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/javascript-basics.md Demonstrates the use of default parameters to provide fallback values for function arguments and rest parameters to collect an indefinite number of arguments into an array. Includes examples of creating users with default roles and summing multiple numbers. ```javascript function createUser(name, role = "user") { return { name, role }; } function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(createUser("Bob")); console.log(sum(1, 2, 3, 4, 5)); ``` -------------------------------- ### Kubernetes Deployment for User Service (YAML) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/architecture.md Example Kubernetes Deployment manifest for a microservice, specifying replica count, container image, ports, and environment variables, including secret references. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: user-service spec: replicas: 3 selector: matchLabels: app: user-service template: metadata: labels: app: user-service spec: containers: - name: user-service image: context7/user-service:v1.2.0 ports: - containerPort: 8080 env: - name: DATABASE_URL valueFrom: secretKeyRef: name: db-credentials key: url ``` -------------------------------- ### JavaScript Object Creation: Literals and Constructors Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/javascript-basics.md Demonstrates two primary ways to create objects in JavaScript: using object literals for direct definition and constructor functions for creating multiple instances with a shared structure. Includes examples of a person object and a Car constructor. ```javascript let person = { name: "John", age: 30, city: "Boston", hobbies: ["reading", "swimming"] }; function Car(brand, model, year) { this.brand = brand; this.model = model; this.year = year; } let myCar = new Car("Honda", "Civic", 2022); ``` -------------------------------- ### JavaScript DOM Event Handling: Click, Submit, Keyboard Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/javascript-basics.md Provides examples of handling common user interactions in the DOM using event listeners. Covers click events on buttons, form submission events, and keyboard events like keydown, including preventing default browser behavior. ```javascript let button = document.querySelector("#submit-btn"); button.addEventListener("click", function(event) { alert("Button clicked!"); event.preventDefault(); }); let form = document.querySelector("#contact-form"); form.addEventListener("submit", function(event) { event.preventDefault(); let name = document.querySelector("#name").value; let email = document.querySelector("#email").value; console.log("Name:", name); console.log("Email:", email); }); document.addEventListener("keydown", function(event) { if (event.key === "Enter") { console.log("Enter key pressed!"); } }); ``` -------------------------------- ### Create Dockerfile for Deployment Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md A basic Dockerfile template for building a production-ready Docker image of the application. It outlines the steps to set up an environment and potentially serve the built application. ```dockerfile ``` -------------------------------- ### Build Application for Production (Bash) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md A command to build the application for production using npm. This typically compiles, minifies, and bundles the project's assets. ```bash npm run build ``` -------------------------------- ### Dockerfile for Context7 App Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md This Dockerfile defines the build and runtime environment for a Context7 application. It uses a multi-stage build to create a lean production image, first building the application with Node.js and then serving the static assets with Nginx. ```Dockerfile FROM node:16-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build FROM nginx:alpine COPY --from=builder /app/build /usr/share/nginx/html COPY nginx.conf /etc/nginx/nginx.conf EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` -------------------------------- ### Implement Project Service (TypeScript) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md Provides a TypeScript service class for managing projects via an API client. It includes methods for fetching, creating, updating, and deleting projects, along with handling API requests and responses. ```typescript // src/services/ProjectService.ts import { ApiClient } from '@context7/core'; import { Project, CreateProjectData } from '../types'; export class ProjectService { private static api = new ApiClient({ baseURL: process.env.REACT_APP_API_URL || 'http://localhost:3000/api' }); static async getProjects(): Promise { const response = await this.api.get('/projects'); return response.data; } static async getProject(id: string): Promise { const response = await this.api.get(`/projects/${id}`); return response.data; } static async createProject(data: CreateProjectData): Promise { const response = await this.api.post('/projects', data); return response.data; } static async updateProject(id: string, data: Partial): Promise { const response = await this.api.put(`/projects/${id}`, data); return response.data; } static async deleteProject(id: string): Promise { await this.api.delete(`/projects/${id}`); } } ``` -------------------------------- ### Create Dashboard Component with Context7 UI Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md This component displays a list of projects fetched from a service. It uses Context7 UI components like Card, Button, and Loading for rendering the project data. The component fetches projects on mount and displays them in a grid layout, with an option to create new projects. ```TypeScript // src/components/Dashboard.tsx import React, { useEffect, useState } from 'react'; import { Button, Card, Loading } from '@context7/ui'; import { ProjectService } from '../services/ProjectService'; import { Project } from '../types'; export function Dashboard() { const [projects, setProjects] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { loadProjects(); }, []); const loadProjects = async () => { try { setLoading(true); const data = await ProjectService.getProjects(); setProjects(data); } catch (error) { console.error('Failed to load projects:', error); } finally { setLoading(false); } }; if (loading) { return ; } return (

My Projects

{projects.map((project) => ( ))}
); } function ProjectCard({ project }: { project: Project }) { return (

{project.name}

{project.description}

Updated {new Date(project.updatedAt).toLocaleDateString()}
); } ``` -------------------------------- ### Implement AuthProvider for Context7 Application Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md Sets up a React context provider for authentication using Context7's auth module, making user data and authentication functions available throughout the application. ```typescript // src/providers/AuthProvider.tsx import React, { createContext, useContext, ReactNode } from 'react'; import { useAuth, AuthProvider as BaseAuthProvider } from '@context7/auth'; import { authConfig } from '../config/auth'; interface AuthContextType { user: User | null; login: (credentials: LoginCredentials) => Promise; logout: () => void; isAuthenticated: boolean; isLoading: boolean; } const AuthContext = createContext(undefined); export function AuthProvider({ children }: { children: ReactNode }) { return ( {children} ); } export function useAuthContext() { const context = useContext(AuthContext); if (!context) { throw new Error('useAuthContext must be used within AuthProvider'); } return context; } ``` -------------------------------- ### Write Project Service Unit Tests (TypeScript) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md Unit tests for the ProjectService using Jest and mocking the ApiClient. These tests verify the functionality of fetching and creating projects by checking API calls and returned data. ```typescript // src/__tests__/ProjectService.test.ts import { ProjectService } from '../services/ProjectService'; import { mockApiClient } from '../__mocks__/ApiClient'; jest.mock('@context7/core'); describe('ProjectService', () => { beforeEach(() => { jest.clearAllMocks(); }); it('should fetch projects successfully', async () => { const mockProjects = [ { id: '1', name: 'Test Project', description: 'A test project' } ]; mockApiClient.get.mockResolvedValue({ data: mockProjects }); const result = await ProjectService.getProjects(); expect(mockApiClient.get).toHaveBeenCalledWith('/projects'); expect(result).toEqual(mockProjects); }); it('should create a project', async () => { const projectData = { name: 'New Project', description: 'A new test project', tags: ['test'], public: false }; const mockProject = { id: '2', ...projectData }; mockApiClient.post.mockResolvedValue({ data: mockProject }); const result = await ProjectService.createProject(projectData); expect(mockApiClient.post).toHaveBeenCalledWith('/projects', projectData); expect(result).toEqual(mockProject); }); }); ``` -------------------------------- ### API Error Response Example Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/api-reference.md Illustrates a typical error response from the API, including an error code, a descriptive message, and specific details about the validation failure. ```json { "error": { "code": "VALIDATION_ERROR", "message": "The email field is required", "details": { "field": "email", "rule": "required" } } } ``` -------------------------------- ### JavaScript Promise Creation and Usage Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/javascript-basics.md Demonstrates how to create a Promise to simulate an asynchronous operation like fetching user data and how to consume it using .then() and .catch() for handling resolved values and errors. ```javascript // Creating a Promise function fetchUserData(userId) { return new Promise((resolve, reject) => { // Simulate API call setTimeout(() => { if (userId > 0) { resolve({ id: userId, name: "John Doe" }); } else { reject(new Error("Invalid user ID")); } }, 1000); }); } // Using Promises fetchUserData(123) .then(user => { console.log("User:", user); return user.name.toUpperCase(); }) .then(upperName => { console.log("Upper name:", upperName); }) .catch(error => { console.error("Error:", error.message); }); ``` -------------------------------- ### React Functional Component with Props (TSX) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md An example of a React functional component named Button, using TypeScript for props definition and demonstrating basic styling and event handling. ```tsx interface ButtonProps { variant: 'primary' | 'secondary'; size: 'sm' | 'md' | 'lg'; disabled?: boolean; onClick: () => void; children: React.ReactNode; } export function Button({ variant, size, disabled, onClick, children }: ButtonProps) { const className = `btn btn--${variant} btn--${size}`; return ( ); } ``` -------------------------------- ### Create Login Form Component with Context7 UI Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md This component provides a user interface for logging in. It utilizes Context7 UI components like Card, Input, Button, and Alert for a seamless user experience. It also integrates with an AuthProvider for handling authentication state and logic, including loading states and error messages. ```TypeScript // src/components/LoginForm.tsx import React, { useState } from 'react'; import { Button, Input, Card, Alert } from '@context7/ui'; import { useAuthContext } from '../providers/AuthProvider'; export function LoginForm() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const { login, isLoading } = useAuthContext(); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(''); try { await login({ email, password }); } catch (err) { setError(err instanceof Error ? err.message : 'Login failed'); } }; return (

Sign In

{error && {error}} setEmail(e.target.value)} required /> setPassword(e.target.value)} required />
); } ``` -------------------------------- ### Input Validation with Zod (TypeScript) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md Shows an example of input validation using the Zod library in TypeScript. It defines a schema for user creation and a function to parse and validate input data. ```typescript // Input validation example import { z } from 'zod'; const createUserSchema = z.object({ name: z.string().min(1).max(100), email: z.string().email(), password: z.string().min(8).max(128) }); export function validateCreateUser(data: unknown) { return createUserSchema.parse(data); } ``` -------------------------------- ### Conventional Commits Format Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md Defines the commit message format using Conventional Commits, including types like feat, fix, docs, style, refactor, test, and chore, with examples. ```markdown [optional scope]: [optional body] [optional footer(s)] **Types:** - `feat`: New feature - `fix`: Bug fix - `docs`: Documentation changes - `style`: Code style changes (formatting, etc.) - `refactor`: Code refactoring - `test`: Adding or updating tests - `chore`: Maintenance tasks **Examples:** ``` feat(auth): add OAuth2 integration fix(api): resolve user creation validation error docs(readme): update installation instructions test(auth): add unit tests for login flow ``` ``` -------------------------------- ### Get Users API Response Source: https://github.com/mwgmorningwood/context7-test/blob/docs/docs/api-reference.md Retrieves a list of users with pagination details. The response includes user data and information about the current page, limit, total items, and whether more pages are available. ```json { "data": [ { "id": "user_123", "name": "John Doe", "email": "john@example.com", "created_at": "2023-01-15T10:30:00Z" } ], "pagination": { "page": 1, "limit": 20, "total": 150, "has_more": true } } ``` -------------------------------- ### Implement WebSocket Service (TypeScript) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md A TypeScript service for managing WebSocket connections using socket.io-client. It handles connecting, disconnecting, listening for events like 'project:updated', and emitting custom events. ```typescript // src/services/WebSocketService.ts import { io, Socket } from 'socket.io-client'; export class WebSocketService { private socket: Socket | null = null; private listeners: Map = new Map(); connect(token: string) { this.socket = io(process.env.REACT_APP_WS_URL || 'ws://localhost:3001', { auth: { token }, transports: ['websocket'] }); this.socket.on('connect', () => { console.log('WebSocket connected'); }); this.socket.on('disconnect', () => { console.log('WebSocket disconnected'); }); this.socket.on('project:updated', (data) => { this.emit('project:updated', data); }); } disconnect() { if (this.socket) { this.socket.disconnect(); this.socket = null; } } on(event: string, callback: Function) { if (!this.listeners.has(event)) { this.listeners.set(event, []); } this.listeners.get(event)!.push(callback); } off(event: string, callback: Function) { const eventListeners = this.listeners.get(event); if (eventListeners) { const index = eventListeners.indexOf(callback); if (index > -1) { eventListeners.splice(index, 1); } } } private emit(event: string, data: any) { const eventListeners = this.listeners.get(event); if (eventListeners) { eventListeners.forEach(callback => callback(data)); } } } export const wsService = new WebSocketService(); ``` -------------------------------- ### Define TypeScript Project Types Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md Defines essential TypeScript interfaces for user data, project details, project creation data, and login credentials. These types ensure data consistency and enable static type checking within the application. ```typescript // src/types/index.ts export interface User { id: string; email: string; name: string; avatar?: string; role: 'admin' | 'user'; createdAt: string; } export interface Project { id: string; name: string; description: string; owner: User; collaborators: User[]; status: 'active' | 'archived' | 'draft'; tags: string[]; createdAt: string; updatedAt: string; } export interface CreateProjectData { name: string; description: string; tags: string[]; public: boolean; } export interface LoginCredentials { email: string; password: string; } ``` -------------------------------- ### React Input Component Source: https://github.com/mwgmorningwood/context7-test/blob/docs/examples/react-components.md A customizable React Input component that accepts props for labels, error messages, helper text, and styling. It uses `forwardRef` for DOM access and `PropTypes` for type checking. ```jsx import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; import './Input.css'; const Input = forwardRef(({ label, error, helperText, required = false, fullWidth = false, type = 'text', ...props }, ref) => { const inputId = props.id || `input-${Math.random().toString(36).substr(2, 9)}`; return (
{label && ( )} {error && ( {error} )} {helperText && !error && ( {helperText} )}
); }); Input.displayName = 'Input'; Input.propTypes = { label: PropTypes.string, error: PropTypes.string, helperText: PropTypes.string, required: PropTypes.bool, fullWidth: PropTypes.bool, type: PropTypes.string, id: PropTypes.string }; export default Input; ``` -------------------------------- ### Unit Testing Button Component (TypeScript) Source: https://github.com/mwgmorningwood/context7-test/blob/docs/CONTRIBUTING.md Provides examples of unit tests for a Button component using Jest and React Testing Library. It demonstrates testing for correct class rendering and click event handling. ```typescript describe('Button component', () => { it('renders with correct variant class', () => { render(); expect(screen.getByRole('button')).toHaveClass('btn--primary'); }); it('calls onClick when clicked', () => { const handleClick = jest.fn(); render(); fireEvent.click(screen.getByRole('button')); expect(handleClick).toHaveBeenCalledTimes(1); }); }); ``` -------------------------------- ### Configure JWT Authentication with Context7 Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/building-your-first-app.md Defines the authentication configuration for a Context7 application, specifying the JWT provider, token storage, API endpoints, and redirection URLs. ```typescript // src/config/auth.ts import { AuthConfig } from '@context7/auth'; export const authConfig: AuthConfig = { provider: 'jwt', tokenStorage: 'localStorage', endpoints: { login: '/api/auth/login', register: '/api/auth/register', refresh: '/api/auth/refresh', logout: '/api/auth/logout' }, redirects: { afterLogin: '/dashboard', afterLogout: '/login', unauthenticated: '/login' } }; ``` -------------------------------- ### JavaScript Data Types and Examples Source: https://github.com/mwgmorningwood/context7-test/blob/docs/tutorials/javascript-basics.md Illustrates JavaScript's built-in data types including numbers, strings (with template literals), booleans, arrays, objects, null, and undefined. Understanding these types is crucial for data manipulation. ```javascript // Numbers let score = 100; let price = 19.99; // Strings let firstName = "Alice"; let lastName = 'Smith'; let fullName = `${firstName} ${lastName}`; // Template literal // Booleans let isActive = true; let isComplete = false; // Arrays let fruits = ["apple", "banana", "orange"]; let numbers = [1, 2, 3, 4, 5]; // Objects let person = { name: "Bob", age: 30, city: "Chicago" }; // Null and Undefined let data = null; // Intentionally empty let result; // Undefined (not assigned) ```