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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@codegenapps/frontend-sdk

v1.0.3

Published

A frontend SDK for seamless API integration, driven by a dynamic schema.

Readme

Frontend SDK

A dynamic, schema-driven frontend SDK for seamless API integration, featuring a fluent query builder.

This SDK is designed to be highly flexible. It dynamically fetches an API specification (like swagger.json or openapi.json) at runtime and builds a powerful, chainable query interface based on it.

Features

  • Dynamic Schema: Initializes from a live API documentation URL. No need to rebuild the SDK when the API changes.
  • Fluent Query Builder: An intuitive, chainable interface (from().select().eq()...) for building complex API requests.
  • Framework Agnostic: Works with any frontend framework (React, Vue, Angular) or plain JavaScript/TypeScript.
  • TypeScript Support: Provides type definitions for core components, although API response types are dynamic.

Installation

npm install @codegenapps/frontend-sdk

Quick Start

The following example demonstrates how to initialize the client and perform a query in a standard JavaScript environment.

import cga from '@codegenapps/frontend-sdk';

// 1. Initialize the client (ideally once when your application starts)
async function initialize() {
  await cga.init({
    // The base URL of your API
    baseUrl: 'http://localhost:8080/api',

    // A function that provides your SDK license key
    licenseKeyProvider: () => 'YOUR_API_KEY',

    // (Optional) A function that provides the JWT for authenticated requests
    tokenProvider: () => localStorage.getItem('jwt_token'),
  });
  console.log('SDK Initialized!');
}

// 2. Perform queries
async function fetchDocuments() {
  try {
    const { data, error } = await cga
      .from('documents')
      .select('id, title')
      .eq('owner_id', 1)
      .order('created_at', { ascending: false })
      .run();

    if (error) {
      console.error('Failed to fetch documents:', error);
      return;
    }

    console.log('Fetched Documents:', data);
  } catch (err) {
    console.error('An unexpected error occurred:', err);
  }
}

initialize().then(async () => {
  await fetchDocuments();
  await loginUser(); // 示範登入功能
});

// 3. Perform login
async function loginUser() {
  const API_KEY = 'YOUR_API_KEY'; 
  const account = '[email protected]';  
  const password = 'testpassword';      

  try {
    console.log(`嘗試使用帳號: ${account}, API Key: ${API_KEY} 登入...`);
    const { data, error } = await cga.auth.login(account, password, API_KEY);

    if (error) {
      console.error('登入失敗:', error);
      return;
    }

    console.log('登入成功! 取得的資料:', data);
    // 您可以在這裡處理登入成功後的邏輯,例如儲存 JWT token
    if (data && data.token) {
      localStorage.setItem('jwt_token', data.token);
      console.log('JWT Token 已儲存到 localStorage。');
    }

  } catch (err) {
    console.error('執行登入時發生意外錯誤:', err);
  }
}

Usage with Frameworks

This SDK is framework-agnostic. The Quick Start example uses standard JavaScript (async/await) that works in any modern environment. Here’s how you might integrate it into popular frameworks.

React Example

In a React component, you can use the useEffect hook to fetch data when the component mounts.

import React, { useState, useEffect } from 'react';
import cga from '@codegenapps/frontend-sdk';

// Initialize the SDK once in your app's entry point (e.g., index.js)
// await cga.init({ ... });

function DocumentsList() {
  const [documents, setDocuments] = useState([]);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function getDocuments() {
      const { data, error } = await cga
        .from('documents')
        .select('id, title')
        .eq('owner_id', 1)
        .run();

      if (error) {
        setError(error);
      } else {
        setDocuments(data);
      }
      setIsLoading(false);
    }

    getDocuments();
  }, []); // The empty dependency array ensures this runs once on mount

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {documents.map(doc => (
        <li key={doc.id}>{doc.title}</li>
      ))}
    </ul>
  );
}

Vue.js Example

In a Vue component (using Composition API), you can use the onMounted hook.

<script setup>
import { ref, onMounted } from 'vue';
import cga from '@codegenapps/frontend-sdk';

// Initialize the SDK once in your app's entry point (e.g., main.js)
// await cga.init({ ... });

const documents = ref([]);
const error = ref(null);
const isLoading = ref(true);

onMounted(async () => {
  const { data, error: fetchError } = await cga
    .from('documents')
    .select('id, title')
    .eq('owner_id', 1)
    .run();

  if (fetchError) {
    error.value = fetchError;
  } else {
    documents.value = data;
  }
  isLoading.value = false;
});
</script>

<template>
  <div v-if="isLoading">Loading...</div>
  <div v-else-if="error">Error: {{ error.message }}</div>
  <ul v-else>
    <li v-for="doc in documents" :key="doc.id">
      {{ doc.title }}
    </li>
  </ul>
</template>

API

Initialization

cga.init(config)

Must be called once before any other methods.

  • config.baseUrl (string, required): The base URL for your API (e.g., https://api.example.com/api). The SDK will automatically try to fetch the schema from {baseUrl_origin}/swagger/doc.json.
  • config.licenseKeyProvider (Function, required): A function that returns your SDK license key.
  • config.tokenProvider (Function, optional): A function that returns the JWT for bearer authentication.
  • config.headers (Object, optional): An object of default headers to be sent with every request.

Querying

.from(tableName: string)

Starts a query chain for a specific resource/table.

.select(fields: string)

Selects which fields to return. If the backend doesn't support field selection, this will be handled client-side.

Filter Methods

  • .eq(column, value)
  • .neq(column, value)
  • .gt(column, value)
  • .gte(column, value)
  • .lt(column, value)
  • .lte(column, value)
  • .like(column, value)
  • .in(column, valuesArray)

.byPk(primaryKeyObject)

Selects a single record by its primary key (or composite primary key).

Example: cga.from('daily_active_user').byPk({ activity_date: '...', user_id: 1, ... })

Data Modification

  • .insert(dataObject | dataArray)
  • .update(dataObject)
  • .delete()

Important: update and delete must be chained with a filter method (like .eq() or .byPk()) to specify which record(s) to modify.

.run()

Executes the query and returns a Promise that resolves to { data, error }. All query chains must end with .run().

Customizing Requests

While the query builder provides methods for common operations, you can further customize requests by passing an options object to the action methods (select, insert, update, delete).

Adding Custom Headers

You can add or override headers for a specific request.

const { data, error } = await cga
  .from('documents')
  .select('id, title', { // <-- Pass options here
    headers: {
      'X-Request-ID': 'custom-request-12345'
    }
  })
  .run();

Adding Custom Query Parameters

For special query parameters not covered by the built-in filter methods, you can use axiosConfig.params. These will be merged with the parameters generated by the builder.

const { data, error } = await cga
  .from('documents')
  .select('id, title', { // <-- Pass options here
    axiosConfig: {
      params: {
        '_cache': false,
        'apiVersion': '2.1'
      }
    }
  })
  .eq('owner_id', 1) // Builder params are still used
  .run();

// The above request will be sent to a URL like:
// /api/documents?_cache=false&apiVersion=2.1&filter=owner_id,eq,1

License

MIT