@cobre-npm/library-nodejs-common
v3.0.1
Published
Nodejs Cobre library without OpenTelemetry
Downloads
1,355
Keywords
Readme
Common library Node js
Is a versatile Node.js library designed to streamline development across various projects. It offers a comprehensive collection of utilities aimed at enhancing productivity and efficiency, catering to a wide range of potential needs.
Some of the utilities available are:
- AWS S3
- AWS Secret Manager
- Config Map (Server side env variables)
Examples
In this section you could see different examples about some utilities that our library offer.
Enjoy!
Split IO
import { SplitAdapter } from './split/entrypoints'
const initSplit = async () => {
const splitAdapter = new SplitAdapter('aws_region', 'split_key_secret_name')
const treatment = await splitAdapter.getTreatment({ clientId: 'clientId', featureName: 'FEATURE_NAME' })
return treatment
}
initSplit()KMS
Descrypt
import { KmsAdapter } from './kms/entrypoints'
const descrypt = async () => {
const kmsAdapter = new KmsAdapter('aws_region')
const descrypt = await kmsAdapter.decrypt('ciphertext_in_base64', 'keyId')
return descrypt
}
descrypt()S3
GetFileUrl
import { S3Adapter } from './s3/entrypoints'
const getFileUrl = async () => {
const s3Adapter = new S3Adapter()
const url = await s3Adapter.getFileUrl({
bucket: 'portal-uploads-qa',
key: 'PXT01/money-movements/csv/2025/01/01b0d26d-684a-48c0-8501-e5b6c469bb1b.csv',
metadata: {}
})
return url
}
getFileUrl()Secret Manager
import { SecretAdapter } from './secretManager/entrypoints'
const initSecretManager = async () => {
const SECRET_NAME = ''
const SECRET_KEY = ''
const secretAdapter = new SecretAdapter()
const secret = await secretAdapter.getSecret({ secretName: `${SECRET_NAME}`, secretKey: `${SECRET_KEY}`)
return secret
}
initSecretManager()Config map
Config map is the server side env variables solution!
import { ConfigMapAdapter } from './configMap/entrypoints'
const initConfigMap = async () => {
const env = 'qa' // qa | prod | dev
const configFile = 'bff' //file name Ex: fineName.properties
const configMapAdapter = new ConfigMapAdapter(env, configFile)
await configMapAdapter.getPropertiesFromConfigServer() //call this once
const specificProp = configMapAdapter.getConfiguration({key: 'specific_prop'})
return specificProp
}
initConfigMap()Config map with Secret Manager
In some cases, when you attempt to access specific properties from your configuration map variables, they might be wrapped inside an interpolation (${EXAMPLE}), indicating that they are secret values. In such cases, you should utilize the Secret Manager to retrieve the secret value.
import { SecretAdapter } from './secretManager/entrypoints'
import { ConfigMapAdapter } from './configMap/entrypoints'
const initSecretEnvVariable = async () => {
const env = 'qa' // qa | prod | dev
const configFile = 'bff' //file name Ex: fineName.properties
const SECRET_NAME = ''
const SECRET_KEY = ''
const configMapAdapter = new ConfigMapAdapter(env, configFile)
await configMapAdapter.getPropertiesFromConfigServer()
const secretEnvValue = configMapAdapter.getConfiguration({key: SECRET_KEY})
const secretAdapter = new SecretAdapter()
const secret = await secretAdapter.getSecret({ secretName: SECRET_NAME, secretKey: secretEnvValue ?? '' })
return secret
}
initSecretEnvVariable()Logging
Our logs utility provide to you the possibility to create logs in a simple way, we used from reference the RFC5424: severity of all levels is assumed to be numerically ascending from most important to least important, the different levels are:
- emerg: 0
- alert: 1
- crit: 2
- error: 3
- warning: 4
- notice: 5
- info: 6
- debug: 7
import { log } from './logging/entrypoints'
// Implement the following code in the main route of the project
app.use(log.loggerMiddleware)
// Use the logs in any case that you consider
log.info({ message: 'Api call fail: ', content: { error: 'Unauthorized' } })CustomErrors
Custom errors utility provide to you a simple way to manage error and save error logs.
import { CustomError } from './error/entrypoints'
const init = () => {
console.log(CustomError.onUnauthorizedError({
location: 'index',
message: 'Unauthorized access',
error: {
message: 'Unauthorized access',
name: 'error'
},
httpCode: 401
}))
}
init()Config map V2
Config map is the server side env variables solution!
import { ConfigMapAdapterv2 } from '@cobre-npm/library-nodejs-common/dist'
const initConfigMap = async () => {
const configMap = await ConfigMapAdapterV2.getInstance({
env: "qa", // qa | prod | dev
fileName: "core-portal-bff",
isLocal: false
})
const secretAdapterRegion = configMap.getConfiguration({ key: "aws_region" })
return { secretAdapterRegion }
}
initConfigMap()Get Internal API Headers
Config map is the server side env variables solution!
import { ConfigMapAdapterv2 } from '@cobre-npm/library-nodejs-common/dist'
const initConfigMap = async () => {
try {
const configMap = await ConfigMapAdapterV2.getInstance({
env: process.env.COBRE_ENV as "prod" | "dev" | "qa",
fileName: process.env.COBRE_APP_CONFIG_FILENAME || "core-portal-bff",
isLocal: true
})
const secretAdapterRegion = configMap.getConfiguration({ key: "aws_region" }) || "us-east-2"
const apigwSecretName = configMap.getConfiguration({ key: "apigw_core_keys" }) || "prod/apigw/core-components/keys"
const authManagerBaseURL = configMap.getConfiguration({ key: "auth_manager_base_url" }) || "https://authmanager.cobre.co"
const headers = await getInternalApiHeaders({
secretAdapterRegion,
apigwSecretName,
authManagerBaseURL,
})
console.log("Headers obtenidos:", headers)
} catch (error) {
console.error("Error ejecutando internalApiService:", error)
}
}
initConfigMap()Feature Flags
Enterprise-grade feature flags with Split.io integration for A/B testing, gradual rollouts, and feature management.
📖 Complete Documentation: Feature Flags Module README
Quick Example
import { FeatureFlags } from '@cobre-npm/library-nodejs-common/dist'
// Simple usage
const isEnabled = await FeatureFlags.isEnabled({
flag: 'new-checkout-flow',
context: { userId: 'user123' }
}, false)
// Use in your code
if (isEnabled) {
// Use new feature
} else {
// Use existing feature
}Key Features
- ✅ Simple API - One-line feature flag evaluation
- ✅ Lambda Optimized - Specialized configuration for serverless
- ✅ AWS Integration - Native Secrets Manager support
- ✅ Real-time Updates - WebSocket streaming with polling fallback
- ✅ Production Ready - Comprehensive logging and error handling
For detailed examples, API reference, Lambda configuration, and advanced usage patterns, see the complete documentation.
logMaskedObject
This utility function processes an object by truncating its values to a specified length and prepending a masking string. It ensures that sensitive data is partially hidden while retaining a portion of the original values for identification purposes.
Function Signature
export const logMaskedObject = (input: unknown, lengthToKeep: number): voidInput
logMaskedObject(
{
username: 'DanielHernandez',
email: '[email protected]',
age: '25',
city: 'Bogota'
},
5
);Output (Info Logged)
{
"username": "*****-*****-*****-*****Danie",
"email": "*****-*****-*****-*****danie",
"age": "*****-*****-*****-*****25",
"city": "*****-*****-*****-*****a"
}OpenTelemetry Setup Example
In your app.ts file, make sure to import and initialize OpenTelemetry before creating your Express application instance.
To set up OpenTelemetry logging and tracing in your application, you can use the following code snippet. This example demonstrates how to configure the environment and initialize the OpenTelemetry adapters.
import dotenv from "dotenv"
const envPath = process.env.NODE_ENV
dotenv.config({ path: `.env.${envPath}` });
import { log, TracingAdapter } from '@cobre-npm/library-nodejs-common/dist'
import packageJson from "../package.json"
const serviceName = "core-portal-bff"
const serviceVersion = packageJson.version
TracingAdapter.init({ serviceName, serviceVersion })
log.initOpentelemetry(serviceName, serviceVersion)This setup ensures that OpenTelemetry is initialized with the correct service name and version, and that logging is configured to use OpenTelemetry's logging capabilities. Make sure to adjust the paths and environment variables according to your project's structure and requirements.
