zerot
    Preparing search index...

    Function rateLimit

    • Creates a rate limiting condition. This condition limits the number of times a specific operation can be performed by a user within a defined window.

      Parameters

      • operation: string

        A string identifying the operation being rate-limited (e.g., "login", "create_post").

      • maxPerWindow: number

        The maximum number of times the operation can be performed per window.

      • OptionalwindowMs: number

        Optional. The time window in milliseconds. Defaults to 60000ms (1 minute).

      Returns (input: any, context: AuthContext) => Promise<boolean>

      A condition function that takes input and authentication context, and returns a Promise resolving to a boolean.

      If the user ID is not available for rate limiting, or if the rate limit is exceeded.

      class CommentService {
      @contract({
      requires: [rateLimit("post_comment", 5)], // Max 5 comments per minute per user (default window)
      })
      async addComment(comment: { postId: string; text: string }, context: AuthContext) {
      // Logic to add comment
      console.log(`User ${context.user?.id} added comment to post ${comment.postId}`);
      }
      }

      class AuthService {
      @contract({
      requires: [rateLimit("login_attempt", 3, 5 * 60 * 1000)], // Max 3 login attempts per 5 minutes
      })
      async login(credentials: any, context: AuthContext) {
      // Logic to login
      }
      }