@altraplay/core
v2.0.2
Published
A centralized NPM package for the utilities frequently used across Altraplay's TypeScript microservices
Maintainers
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/coreConfiguration
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 therandomStringfunction fromsrc/random.ts.pushLogs: Accesses thepushLogsmethod of aKafkaLoggerinstance.S3: Accesses thecreateS3Clientfunction fromsrc/aws/s3.ts, which now uses Bun's native S3 client.exec: Accesses theexecmethod of aScyllainstance.send: Accesses thesendmethod of a Kafka producer instance.redis: A Redis client instance using Bun's native client withget,set, anddelmethods.validate.isVisible: Accesses theisVisiblefunction fromsrc/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 auid(the content owner's ID) and avisibilityarray.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
visibilityarray.
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') // falserandomString (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'sS3Options, with an addeddefaultBucketproperty.
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: AScyllaClientOptionsobject 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 KafkaclientId.config: A configuration object, typicallyutils.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, typicallyutils.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, typicallyutils.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-driverkafkajs
