npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@altraplay/core

v2.0.2

Published

A centralized NPM package for the utilities frequently used across Altraplay's TypeScript microservices

Readme

@altraplay/core

A centralized NPM package for the utilities frequently used across our TypeScript microservices.

Installation

You can install this package using npm or bun:

npm install @altraplay/core
# or
bun add @altraplay/core

Configuration

This package now uses a centralized configuration system that sources settings from environment variables. A config.ts file is responsible for reading and validating these variables. When you initialize InitService, it automatically loads the necessary configuration.

Required Environment Variables:

  • KAFKA_URL: Comma-separated list of Kafka broker URLs.
  • LOGS_KAFKA_URL: Comma-separated list of Kafka broker URLs for the logging service.
  • [SERVICE_NAME]_DB_URL: Comma-separated list of ScyllaDB/Cassandra contact points.
  • [SERVICE_NAME]_DB_DC: The datacenter for the ScyllaDB/Cassandra connection.
  • [SERVICE_NAME]_DB_USER: The username for the ScyllaDB/Cassandra connection.
  • [SERVICE_NAME]_DB_PASS: The password for the ScyllaDB/Cassandra connection.
  • [SERVICE_NAME]_DB_KS: The keyspace for the ScyllaDB/Cassandra connection.
  • [SERVICE_NAME]_REDIS_URL: The connection URL for Redis.

The [SERVICE_NAME] placeholder should be replaced with the uppercase version of the serviceName you provide to the InitService constructor.

Modules and Functions

InitService (Core Initialization)

The InitService class provides a convenient way to initialize and access various core utilities within your microservice. It aggregates functionalities from other modules and manages configuration.

new InitService(serviceName: string, config?: Partial<ReturnType<typeof getConfig>>)

Initializes the service.

  • serviceName: The name of the service, used to construct environment variable names for database configuration.
  • config: An optional configuration object that can override the values loaded from environment variables.

Aggregated Methods & Properties:

  • config: The fully resolved configuration object.
  • randomString: Accesses the randomString function from src/random.ts.
  • pushLogs: Accesses the pushLogs method of a KafkaLogger instance.
  • S3: Accesses the createS3Client function from src/aws/s3.ts, which now uses Bun's native S3 client.
  • exec: Accesses the exec method of a Scylla instance.
  • send: Accesses the send method of a Kafka producer instance.
  • redis: A Redis client instance using Bun's native client with get, set, and del methods.
  • validate.isVisible: Accesses the isVisible function from src/validate.ts.
import { InitService } from '@altraplay/core'

const utils = new InitService('my-microservice')

// Example usage of aggregated methods:
const randomStr = utils.randomString()
await utils.pushLogs('info', 'my-route', 'my-operation', 'Service started')
const s3Client = utils.S3({ defaultBucket: 'my-bucket' })
const dbResult = await utils.exec('SELECT * FROM users')
await utils.send([{ cmd: 'add', body: { id: '123' } }], 'user-topic')

Re-exported Modules: The Scylla class, randomString, and createRedisClient function are also directly re-exported from the main @altraplay/core package for direct import if preferred.

import { Scylla, randomString, createRedisClient } from '@altraplay/core'

validate.isVisible

Checks if a piece of content should be visible to a specific user.

isVisible(content?: Record<string, any> | null, viewer?: string | null): boolean

  • content: An object containing content details, which must include a uid (the content owner's ID) and a visibility array.
  • viewer: The ID of the user attempting to view the content.

Returns true if:

  • The viewer is the owner of the content (content.uid === viewer).
  • The content is public (content.visibility?.includes('pub')).
  • The viewer's ID is in the visibility array.
const { validate } = utils // from new InitService('my-microservice')

const publicContent = { uid: 'user-a', visibility: ['pub'] }
const privateContent = { uid: 'user-a', visibility: ['user-b'] }

validate.isVisible(publicContent, 'user-c') // true
validate.isVisible(privateContent, 'user-a') // true
validate.isVisible(privateContent, 'user-b') // true
validate.isVisible(privateContent, 'user-c') // false

randomString (Random Utility)

Generates a cryptographically secure random string using a diverse character set.

randomString(min = 16, max = 32): string

Generates a random string with a length between min and max (inclusive).

  • min: Minimum length of the generated string (default: 16).
  • max: Maximum length of the generated string (default: 32).

createS3Client (AWS S3 Utility)

Creates an S3 client instance using Bun's native S3 client, automatically configuring credentials from environment variables. It provides convenient methods for get, put, and delete operations, including support for generating presigned URLs.

createS3Client(config?: S3Config)

  • config: An optional configuration object extending Bun's S3Options, with an added defaultBucket property.

Returned Methods:

  • get(params: GetParameters): Promise<GetOutput>: Retrieves an object. Can return the body in various formats or a presigned URL.
  • put(params: PutParameters): Promise<PutOutput>: Uploads an object or generates a presigned URL for uploading.
  • delete(params: DeleteParameters): Promise<DeleteOutput>: Deletes an object or generates a presigned URL for deletion.
const s3 = createS3Client({ defaultBucket: 'my-default-bucket' })

// Upload a file
await s3.put({ Key: 'my-file.txt', Body: 'Hello, World!' })

// Get a file
const { Body } = await s3.get({ Key: 'my-file.txt', ResponseType: 'text' })
console.log(Body) // 'Hello, World!'

// Generate a presigned URL for a GET request
const { PresignedUrl } = await s3.get({
	Key: 'my-file.txt',
	PresignConfig: { expiresIn: 60 } // URL expires in 60 seconds
})

Scylla (ScyllaDB/Cassandra Utility)

The Scylla class provides a robust interface for interacting with ScyllaDB or Apache Cassandra databases.

new Scylla(config: ScyllaClientOptions)

new Scylla(serviceName: string)

Initializes a new database client instance. It can be initialized either with a full configuration object or by passing a serviceName, which will be used to resolve database credentials from environment variables.

  • config: A ScyllaClientOptions object containing connection details.
  • serviceName: The name of the service, used to construct environment variable names (e.g., MY_APP_DB_URL).

exec

Executes a database query or a batch of queries. This method is overloaded to support single queries, detailed results with pagination, and batch operations.

const { exec } = utils // from new InitService('my-microservice')

// Fetching a single user
const user = await exec<{ id: string; name: string }>('SELECT id, name FROM users WHERE id = ?', [
	'user123'
])

createProducer (Kafka Utility)

Creates a Kafka producer instance.

createProducer(serviceName: string, config: Config): { send: (data: ..., topic?: string) => Promise<void>; producer: Producer }

  • serviceName: The name of the service, used as the Kafka clientId.
  • config: A configuration object, typically utils.config.kafka.

The send function now uses ZSTD compression for messages.

const { send } = utils // from new InitService('my-microservice')
await send([{ cmd: 'add', body: { userId: '123', event: 'login' } }], 'user-events')

KafkaLogger (Logging Utility)

A comprehensive logging class that pushes structured log entries to a Kafka topic and logs to the console.

new KafkaLogger(serviceName: string, config: Config)

Initializes the Kafka logger.

  • serviceName: The name of the service generating the logs.
  • config: A configuration object, typically utils.config.logKafka.

pushLogs

Pushes one or more log entries to the 'logs' Kafka topic, using ZSTD compression.

createRedisClient (Redis Utility)

Creates a Redis client instance using Bun's native Redis client.

createRedisClient(serviceName: string, config: RedisConfig, pushLogs: Function): { get: <T>(key: string) => Promise<T | null>; set: <T>(key: string, value: T, ttlSeconds?: number) => Promise<'OK' | null>; del: (key: string | string[]) => Promise<number>; client: Redis | null }

  • serviceName: The name of the service, used for logging errors.
  • config: A configuration object, typically utils.config.redis.
const { redis } = utils // from new InitService('my-microservice')
await redis.set('user:123', { name: 'John Doe' }, 3600)
const user = await redis.get('user:123')

Dependencies

  • cassandra-driver
  • kafkajs