200.Land

Snippets

nest-api-gateway-roles.ts

Thu Sep 07 2023

The TypeScript code sets up a role-based access control in a NestJS application using a custom guard. It defines a RolesGuard class that leverages metadata reflection to determine the necessary roles for accessing particular routes. It retrieves the user roles from the AWS API Gateway request context, specified in the headers, and checks if the user has at least one of the roles required to access a route, thus facilitating role-based authorization.

api-cdk.ts

Thu Sep 07 2023

The TypeScript code uses AWS CDK to create an AWS API Gateway with a set of predefined REST API resources (like "signup", "login") each supporting specific HTTP methods. It sets up CORS, associates the API with a custom domain using a DNS certificate, and creates a DNS record in Route 53. The API integrates with a Lambda function handler and optionally protects resources with a Cognito User Pools authorizer. It configures a usage plan to throttle the API requests to a specified rate limit.

qa-chat-pinecone.ts

Thu Sep 07 2023

Setup up a chat system using the GPT-3.5-turbo-16k model to respond to user queries. It initializes necessary components like a vector store and a QA chain, and includes a query method to fetch generated responses to questions.

crawl-query-gpt.ts

Tue Aug 08 2023

The code defines three classes: PineconeCrawler, DiskCrawler, and Neo4jCrawler, each utilizing the PuppeteerCrawler to scrape web pages from specified URLs. They process webpage content differently: storing embeddings in a Pinecone database, saving them locally with HNSWLib, and adding page metadata to a Neo4j graph database, respectively.

zap-alerts.ts

Wed Aug 02 2023

This Node.js script uses Puppeteer and OWASP ZAP API to scan a list of URLs (from "urls.json") for security vulnerabilities. It visits each URL, triggers ZAP scans, and appends alerts along with the URL found to a newline-delimited JSON file ("zap-report.jsonl").

isfibonacci.ts

Thu Sep 08 2022

The JavaScript code defines two utility functions to identify special numeric properties. The isPerfectSquare function determines whether an input number is a perfect square, while the isFibonacci function leverages the former to identify if a number is part of the Fibonacci sequence, following a known mathematical property that relates Fibonacci numbers with perfect squares.

to-tuple-type.ts

Wed Feb 03 2021

This TypeScript code defines a type alias ToTupleType that takes two type parameters: B, an object type, and F, a tuple of key strings representing keys of B. It maps over the tuple F, creating a new tuple type where each element is the type of the corresponding property in B. It essentially helps in transforming an object into a tuple type with a specific set of properties.

anomaly-detector.ts

Mon Nov 09 2020

This TypeScript code defines an AnomalyDetector class that identifies anomalies in a dataset based on the specified sensitivity level. It uses a specified numeric key to extract values from dataset objects and compute the average and standard deviation of these values to identify anomalies, which are then filtered and can be retrieved using the getAnomalies method. It leverages an interface to type the options parameter used in the constructor to instantiate the class with necessary settings.

collatz-conjecture.ts

Mon Oct 26 2020

This JavaScript code defines a CollatzConjecture class that implements the iterable protocol to generate a sequence according to the Collatz conjecture rules starting from a given number. When instantiated with a start number and iterated over, it produces a series of numbers according to the conjecture, which ends when the series reaches the number 1. It demonstrates usage by creating a series starting from 13 and logging it to the console.

deduplicate.ts

Tue Apr 14 2020

The TypeScript code defines a type alias OccurrenceMap and a function getDuplicates. The function takes a readonly array, calculates the occurrence of each element, and returns an object that maps each element (that appears more than once) to its frequency. It leverages TypeScript's utility types to work with both number and string arrays.

overriding-hasinstance.ts

Tue Feb 04 2020

The JavaScript code explores JavaScript's instanceof operator and the [Symbol.hasInstance] method. It defines three classes (A, B, and MyClass) and an array of objects. It customizes the behavior of instanceof for MyClass using [Symbol.hasInstance] to include objects matching certain criteria. Finally, it filters an array using this customized instanceof check, demonstrating polymorphic behavior based on dynamic type checking.

async-iterator.ts

Mon Feb 03 2020

The JavaScript code defines an async iterable class CustumIterable parameterized over two types, which facilitates iteration over a sequence of async fetched items defined by a starting index and next index computation function. A showDogs function demonstrates its usage, iterating over dog objects asynchronously fetched by ID until undefined is returned, signaling the end of the iterable.

class-emits-event.ts

Thu Jan 30 2020

The JavaScript code defines a MyClass class extending Node.js' EventEmitter to manage custom events. It has a method someMethod that emits an "alerts" event with the class state as argument. After instantiation, a timer is set to invoke someMethod after a delay, which triggers a console log in an event listener set up to listen for "alerts" events, demonstrating a basic event-driven programming setup.

parquet-transform.ts

Wed Jan 29 2020

The JavaScript code reads a JSON file using a stream, transforms it into a Parquet format leveraging a defined schema, and then writes it to a Parquet file. The transformation utilizes the "parquetjs" library for Parquet format handling and "stream-json" for efficient JSON streaming, thereby converting a large JSON file to a Parquet file with specified schema mapping, which can be more efficient for storage and querying.

factory.ts

Wed Nov 20 2019

The TypeScript code defines two classes, Approach1 and Approach2, both implementing the IApproach interface, which takes IParams as input and returns IOutput. Another class, ServiceThatCombines, also implements IApproach, utilizing a map to dynamically choose between Approach1 and Approach2 based on the type parameter in IParams to execute the do method, facilitating a strategy pattern to determine the approach at runtime.

strict-type.ts

Wed Nov 20 2019

The TypeScript code defines an interface INiceAndLoose and a utility type Strict which transforms the properties of a type to be non-nullable and required. An instance of the Strict type, derived from INiceAndLoose, is created, showcasing that the properties must now be non-nullable and defined.

props-protector.ts

Mon Sep 02 2019

The TypeScript code defines a PropsProtector class to manage and validate property overrides through BaseProps and UserProps derived from an IProps interface. The AbstractClass sets immutable base properties, while ConcreteClass sets user properties. It then creates an instance of ConcreteClass, which logs a merged object of base and user properties, ensuring no base properties are overridden.

leaky-bucket.ts

Tue Jun 04 2019

The TypeScript code defines a rate limiter using the leaky bucket algorithm. It has LeakyBucket and LeakyBucketTask classes. Tasks with a specified number of retries are added to the bucket and executed at intervals defined by rateMs. The bucket executes tasks one by one, retrying failed tasks until they succeed or exhaust their retries, and removes completed tasks. It allows for the addition of new tasks and stopping the task execution.