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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@heliyos/heliyos-api-core

v1.0.33

Published

Heliyos's core api functions and middlewares. Its a private package hosted on npm.

Downloads

2,322

Readme

@heliyos/heliyos-api-core

This repository contains Heliyos's core API functions and middlewares. It's a private package hosted on npm.

Table of Contents

Installation

  1. Add .npmrc file in your project root:
registry.npmjs.org/:_authToken=${NPM_TOKEN}
  1. Install the package:
npm install @heliyos/heliyos-api-core

Core Modules

App Configuration

The core app setup provides middleware configuration and error handling.

import { core_app } from "@heliyos/heliyos-api-core";
import userRoutes from "./routes/user";

const routes = [userRoutes];

const options = {
  staticDir: true, // Enable static file serving
  skipExternals: false, // Skip external middleware
  skipInternals: false, // Skip internal middleware
  excludedHeaderRegexString: "", // Regex for excluding headers
};

const app = express();
await core_app(app, routes, options);

Authentication

Handles user authentication with support for Basic Auth, Bearer tokens, and API keys.

import { authentication } from "@heliyos/heliyos-api-core";

// Use as middleware
app.use(authentication);

// Required environment variables:
// SECRET_OF_SERVER
// BASE_URL_AUTH_SERVER
// SECRET_OF_AUTH_SERVER

Authorization

Role-based access control for resources.

import { authorizeUser } from "@heliyos/heliyos-api-core";

const checkAccess = async (
  organizationId: number,
  userId: number,
  action: string
) => {
  const { isAllowed, userRole } = await authorizeUser(
    organizationId,
    userId,
    action
  );
  return isAllowed;
};

Axios HTTP Client

Pre-configured Axios instances for internal services.

import { axios } from "@heliyos/heliyos-api-core";

// Available instances:
await axios.authServer.get("/endpoint");
await axios.platformServer.post("/endpoint", data);
await axios.agentServer.put("/endpoint", data);

// Required environment variables for each server:
// BASE_URL_AUTH_SERVER + SECRET_OF_AUTH_SERVER
// BASE_URL_PLATFORM_SERVER + SECRET_OF_PLATFORM_SERVER
// BASE_URL_AGENT_SERVER + SECRET_OF_AGENT_SERVER
// BASE_URL_USERS_SERVER + SECRET_OF_USERS_SERVER

Database (Knex)

Database connection and query builder with pagination support.

import { knex } from "@heliyos/heliyos-api-core";

// Regular queries
const users = await knex("users").where({ active: true });

// With pagination
const results = await knex("users")
  .where({ active: true })
  .paginate(page, limit);

// Results format:
// {
//   data: Array<T>,
//   meta: {
//     page: number,
//     limit: number,
//     offset: number,
//     count: number
//   }
// }

// Required environment variables:
// DATABASE_URL

Validation

Input validation using Joi.

import { validate, joiObject } from "@heliyos/heliyos-api-core";

const schema = (joi) =>
  joi.object({
    name: joi.string().required(),
    email: joi.string().email().required(),
  });

// Validate input
validate(inputData, schema);

// Using joiObject directly
const customSchema = joiObject.object({
  // schema definition
});

Redis Client

Redis connection management.

import { createRedisClient } from "@heliyos/heliyos-api-core";

const redisClient = createRedisClient({
  url: "redis://localhost:6379",
});

Pusher

Real-time event broadcasting.

import { pusherTrigger, pusherTriggerBatch } from "@heliyos/heliyos-api-core";

// Single event
await pusherTrigger("channel-name", "event-name", { data: "payload" });

// Batch events
const batch = [
  { channel: "channel1", name: "event1", data: {} },
  { channel: "channel2", name: "event2", data: {} },
];
await pusherTriggerBatch(batch);

// Required environment variables:
// PUSHER_APP_ID
// PUSHER_KEY
// PUSHER_SECRET
// PUSHER_CLUSTER

SQS (Message Queue)

AWS SQS integration for message queuing.

import { SQSUtil } from "@heliyos/heliyos-api-core";

const sqs = new SQSUtil();

// Write message
await sqs.write(
  {
    resource: "users",
    type: "INSERT",
    objectId: { name: "user_id", value: "123" },
    data: { name: "John" },
  },
  "queue-url",
  "optional-group-id"
);

// Read message
const messages = await sqs.read("queue-url");

// Delete message
await sqs.delete(receiptHandle, "queue-url");

Email Services

Email sending with template support using Resend.

import { resendSendEmail } from "@heliyos/heliyos-api-core";

await resendSendEmail(
  ["[email protected]"],
  "template-id",
  { name: "John" },
  "Email Subject"
);

// Required environment variables:
// RESEND_API_KEY
// RESEND_FROM_RECIPIENT

Environment Management

Load environment variables from AWS Secrets Manager.

import { loadAppEnv } from "@heliyos/heliyos-api-core";

const env = await loadAppEnv();

// Required environment variables:
// ENV_SECRET_NAME

Logging

Structured logging with Winston.

import { logger } from "@heliyos/heliyos-api-core";

logger.info("Message", { meta: "data" });
logger.error("Error occurred", { error });
logger.warn("Warning message");

Development

To test changes locally:

  1. Build the package:
npm run build
  1. Create a tarball:
npm pack --pack-destination .
  1. Install in your project:
npm install /path/to/heliyos-api-core/heliyos-ai-heliyos-api-core-1.0.5.tgz

Publishing

To publish updates (admin only):

  1. Update version in package.json
npm version patch|minor|major
  1. Build the project
npm run build
  1. Publish
npm publish

Mongoose Setup and Usage Guide

This guide covers the setup and usage of Mongoose in your application, including connection management, models, queries, and utility functions.

Setup

  1. Set environment variables:
env
MONGO_DATABASE_URL=mongodb://localhost:27017/your_database

Creating Models

  1. Define your interface and schema:
import { Document, Schema, model } from "@heliyos/heliyos-api-core";
interface IUser extends Document {
  name: string;
  email: string;
  createdAt: Date;
}
const userSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
});
export const UserModel = model("User", userSchema);

Querying

Basic queries:

// Find documents
const users = await UserModel.find({ name: "John" });
// Find one document
const user = await UserModel.findOne({ email: "[email protected]" });
// Create document
const newUser = await UserModel.create({
  name: "John",
  email: "[email protected]",
});

Using type-safe queries:

import { FilterQuery, UpdateQuery } from "@heliyos/heliyos-api-core";
// Type-safe find
const users = await UserModel.find({
  name: "John",
} as FilterQuery<IUser>);
// Type-safe update
await UserModel.updateOne(
  { id: userId } as FilterQuery<IUser>,
  { name: "Jane" } as UpdateQuery<IUser>
);

Pagination

Use the paginate method on any query:

const paginatedUsers = await UserModel.find().paginate<IUser>(1, 10);
console.log(paginatedUsers.data); // Array of users
console.log(paginatedUsers.meta); // { page, limit, offset, count }

Types

Common types available for import:

import {
  Document,
  Schema,
  Model,
  FilterQuery,
  UpdateQuery,
  Connection,
} from "@heliyos/heliyos-api-core";

Pagination Interface

interface Pagination<T> {
  data: T[];
  meta: {
    page: number;
    limit: number;
    offset: number;
    count: number;
  };
}