Custom Dev Projects

Project Templates

Filter by:
Node.js Dockerfile
A Dockerfile for a Node.js application with best practices for production
# Node.js Dockerfile
  FROM node:18-alpine as builder
  
  WORKDIR /app
  
  COPY package*.json ./
  RUN npm ci
  
  COPY . .
  RUN npm run build
  
  # Production stage
  FROM node:18-alpine as runner
  
  WORKDIR /app
  
  ENV NODE_ENV=production
  
  COPY --from=builder /app/package*.json ./
  COPY --from=builder /app/node_modules ./node_modules
  COPY --from=builder /app/dist ./dist
  
  USER node
  
  CMD ["node", "dist/index.js"]
dockernodeproduction
Python Flask Dockerfile
A Dockerfile for a Python Flask application with best practices
# Python Flask Dockerfile
  FROM python:3.11-slim as builder
  
  WORKDIR /app
  
  COPY requirements.txt .
  RUN pip install --no-cache-dir -r requirements.txt
  
  COPY . .
  
  # Production stage
  FROM python:3.11-slim
  
  WORKDIR /app
  
  ENV PYTHONUNBUFFERED=1 \
      PYTHONDONTWRITEBYTECODE=1 \
      PIP_NO_CACHE_DIR=1
  
  COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
  COPY --from=builder /app .
  
  EXPOSE 5000
  
  CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:5000"]
dockerpythonflask
Python CLI Template
A template for creating command-line applications in Python with argparse
#!/usr/bin/env python3
  """
  CLI Application Template
  
  A template for creating command-line applications in Python with argparse.
  """
  
  import argparse
  import sys
  import logging
  from typing import List, Optional
  
  # Configure logging
  logging.basicConfig(
      level=logging.INFO,
      format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
      handlers=[logging.StreamHandler()]
  )
  logger = logging.getLogger(__name__)
  
  def parse_args(args: List[str]) -> argparse.Namespace:
      """Parse command line arguments."""
      parser = argparse.ArgumentParser(
          description="Description of your CLI application",
      )
      
      # Add arguments
      parser.add_argument(
          "-f", "--file",
          help="Input file path",
          type=str,
          required=True
      )
      
      parser.add_argument(
          "-o", "--output",
          help="Output file path",
          type=str
      )
      
      parser.add_argument(
          "--verbose",
          help="Enable verbose output",
          action="store_true"
      )
      
      return parser.parse_args(args)
  
  def main(args: Optional[List[str]] = None) -> int:
      """Main entry point for the application."""
      if args is None:
          args = sys.argv[1:]
      
      args = parse_args(args)
      
      # Set logging level based on verbosity
      if args.verbose:
          logger.setLevel(logging.DEBUG)
          logger.debug("Verbose output enabled")
      
      try:
          # Your application logic here
          logger.info(f"Processing file: {args.file}")
          
          # Example: Read the input file
          with open(args.file, 'r') as f:
              content = f.read()
              
          # Process the content
          processed_content = content.upper()  # Example transformation
          
          # Write the output
          output_path = args.output or f"{args.file}.out"
          with open(output_path, 'w') as f:
              f.write(processed_content)
              
          logger.info(f"Output written to {output_path}")
          
          return 0
      
      except Exception as e:
          logger.error(f"Error: {str(e)}")
          return 1
  
  if __name__ == "__main__":
      sys.exit(main())
pythonclitemplate
Next.js API Route Template
A template for creating API routes in Next.js with proper error handling
// Next.js API Route Template
  import { NextRequest, NextResponse } from 'next/server';
  
  // Define the expected request body type
  interface RequestBody {
    // Define your request body properties here
    name: string;
    email: string;
  }
  
  // Define the response type
  interface ApiResponse {
    success: boolean;
    message: string;
    data?: any;
  }
  
  /**
   * API handler for processing requests
   */
  export async function POST(req: NextRequest) {
    try {
      // Parse the request body
      const body = await req.json() as RequestBody;
      
      // Validate the request body
      if (!body.name || !body.email) {
        return NextResponse.json({
          success: false,
          message: 'Name and email are required',
        } as ApiResponse, { status: 400 });
      }
      
      // Process the request (replace with your actual logic)
      const data = {
        id: Math.random().toString(36).substr(2, 9),
        name: body.name,
        email: body.email,
        createdAt: new Date().toISOString()
      };
      
      // Return a successful response
      return NextResponse.json({
        success: true,
        message: 'Data processed successfully',
        data
      } as ApiResponse, { status: 200 });
      
    } catch (error) {
      console.error('API Error:', error);
      
      // Return an error response
      return NextResponse.json({
        success: false,
        message: 'Internal server error',
      } as ApiResponse, { status: 500 });
    }
  }
  
  /**
   * GET handler for retrieving data
   */
  export async function GET(req: NextRequest) {
    try {
      // Get query parameters
      const searchParams = req.nextUrl.searchParams;
      const id = searchParams.get('id');
      
      // Fetch data based on query parameters (replace with your actual logic)
      const data = id 
        ? { id, name: 'Example User', email: 'user@example.com' }
        : [
            { id: '1', name: 'User 1', email: 'user1@example.com' },
            { id: '2', name: 'User 2', email: 'user2@example.com' }
          ];
      
      // Return the data
      return NextResponse.json({
        success: true,
        message: 'Data retrieved successfully',
        data
      } as ApiResponse, { status: 200 });
      
    } catch (error) {
      console.error('API Error:', error);
      
      // Return an error response
      return NextResponse.json({
        success: false,
        message: 'Internal server error',
      } as ApiResponse, { status: 500 });
    }
  }
next.jsapitypescript