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

hedracms-sdk

v1.0.8

Published

The **HedraCMS SDK** enables seamless integration of HedraCMS content into your frontend applications. With support for retrieving content, attributes, and paginated data, this SDK provides developers with the tools to efficiently manage CMS-driven data a

Downloads

600

Readme

HedraCMS SDK Documentation

The HedraCMS SDK enables seamless integration of HedraCMS content into your frontend applications. With support for retrieving content, attributes, and paginated data, this SDK provides developers with the tools to efficiently manage CMS-driven data across multiple frameworks.


Table of Contents


Installation

Install the SDK using npm or yarn:

npm install hedracms-sdk
# or
yarn add hedracms-sdk

Setup

Before using the SDK, initialize it in your application. The initialization ensures the SDK is ready with your account credentials and API configuration.

Initialize HedraCMS

To initialize the SDK, use the initialize method:

import { initialize } from 'hedracms-sdk';

initialize({
  accountId: 'YOUR_ACCOUNT_ID',
  accessToken: 'YOUR_ACCESS_TOKEN',
  baseUrl: 'https://api.hedracms.com/api/v1',
});

Parameters:

  • accountId: Your unique HedraCMS account identifier.
  • accessToken: The authentication token for API access.
  • baseUrl: The base URL of the HedraCMS API.

Example

import { initialize } from 'hedracms-sdk';

initialize({
  accountId: '12345',
  accessToken: 'abcdef12345',
  baseUrl: 'https://api.hedracms.com/api/v1',
});

Methods

1. Retrieve Content

Use the getContent method to retrieve single or multiple pages. The keys in the response directly match the keys you provide in the request.

Usage

import { getContent } from 'hedracms-sdk';

const content = await getContent(['homepage', 'aboutpage']);
console.log(content.homepage, content.aboutpage);

Parameters:

  • pageIds: An array of page IDs to retrieve.
  • Options:
    • batch: Boolean. When true, sends a batch request to fetch all pages in one call.
    • language: String. Specify the language to retrieve localized content.

Example

const pages = await getContent(['menucontent', 'footer'], { batch: true, language: 'en' });
console.log(pages.menucontent, pages.footer);

2. Retrieve Attributes

The getAttribute method fetches custom key-value pairs from your CMS.

Usage

import { getAttribute } from 'hedracms-sdk';

const attributes = await getAttribute(['siteSettings', 'seoConfig']);
console.log(attributes.siteSettings, attributes.seoConfig);

Parameters:

  • attributeKeys: An array of attribute keys to retrieve.
  • Options:
    • batch: Boolean. When true, sends a batch request to fetch all attributes in one call.

Example

const siteAttributes = await getAttribute(['branding', 'siteMeta'], { batch: true });
console.log(siteAttributes.branding, siteAttributes.siteMeta);

3. Retrieve Paginated Data

Use the getContentList method to retrieve paginated data for multi-page content such as blogs or products.

Usage

import { getContentList } from 'hedracms-sdk';

const paginatedData = await getContentList('blogpage', { page: 1, limit: 10 });
console.log(paginatedData.data, paginatedData.pagination);

Parameters:

  • contentType: The type of content to retrieve (e.g., blogpage).
  • Options:
    • page: Number. The page number to retrieve.
    • limit: Number. The number of items per page.
    • language: String. Specify the language for localized content.

Response

  • data: An array of items for the current page.
  • pagination: Metadata including total count, total pages, and current page.

Example

interface BlogPost {
  id: string;
  title: string;
}

const blogPosts = await getContentList<BlogPost>('blogpage', { page: 2, limit: 5 });
console.log(blogPosts.data, blogPosts.pagination);

Framework Examples

Next.js

'use client';

import { ReactNode, useEffect, useState } from 'react';
import { initialize, isInitialized } from 'hedracms-sdk';

export function HedraCMSProvider({ children }: { children: ReactNode }) {
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    if (!isInitialized()) {
      try {
        initialize({
          accountId: process.env.NEXT_PUBLIC_ACCOUNT_ID!,
          accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN!,
          baseUrl: process.env.NEXT_PUBLIC_HEDRACMS_BASE_URL!,
        });
        setInitialized(true);
      } catch (error) {
        console.error('Failed to initialize HedraCMS:', error);
      }
    } else {
      setInitialized(true);
    }
  }, []);

  if (!initialized) {
    return null;
  }

  return <>{children}</>;
}

React

import React, { useEffect, useState } from 'react';
import { initialize, isInitialized } from 'hedracms-sdk';

function App({ children }: { children: React.ReactNode }) {
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    if (!isInitialized()) {
      try {
        initialize({
          accountId: process.env.REACT_APP_ACCOUNT_ID!,
          accessToken: process.env.REACT_APP_ACCESS_TOKEN!,
          baseUrl: process.env.REACT_APP_HEDRACMS_BASE_URL!,
        });
        setInitialized(true);
      } catch (error) {
        console.error('Failed to initialize HedraCMS:', error);
      }
    } else {
      setInitialized(true);
    }
  }, []);

  if (!initialized) {
    return <div>Loading...</div>;
  }

  return <div>{children}</div>;
}

Vue

// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { initialize } from 'hedracms-sdk';

initialize({
  accountId: import.meta.env.VITE_ACCOUNT_ID!,
  accessToken: import.meta.env.VITE_ACCESS_TOKEN!,
  baseUrl: import.meta.env.VITE_HEDRACMS_BASE_URL!,
});

createApp(App).mount('#app');

Angular

// main.ts
import { initialize } from 'hedracms-sdk';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

initialize({
  accountId: process.env.NG_APP_ACCOUNT_ID!,
  accessToken: process.env.NG_APP_ACCESS_TOKEN!,
  baseUrl: process.env.NG_APP_HEDRACMS_BASE_URL!,
});

platformBrowserDynamic().bootstrapModule(AppModule).catch((err) => console.error(err));

Plain JavaScript

import { initialize } from 'hedracms-sdk';

initialize({
  accountId: 'YOUR_ACCOUNT_ID',
  accessToken: 'YOUR_ACCESS_TOKEN',
  baseUrl: 'https://api.hedracms.com/api/v1',
});

// Fetch content
import { getContent } from 'hedracms-sdk';

const loadContent = async () => {
  const [homepage] = await getContent(['homepage']);
  document.getElementById('content').innerHTML = `<h1>${homepage.title}</h1>`;
};

loadContent();

Error Handling

All methods throw errors with detailed messages. Use try-catch for handling errors gracefully.

import { getContent } from 'hedracms-sdk';

try {
  const content = await getContent(['homepage']);
} catch (error) {
  console.error('Error retrieving content:', error);
}

Key Notes

  • The SDK enforces key-based responses, ensuring the key you request matches the key in the response.
  • Batch operations improve performance when fetching multiple pages or attributes.

Example:

import { getContent, getAttribute } from 'hedracms-sdk';

const pages = await getContent(['homepage', 'contactpage'], { batch: true });
console.log(pages.homepage, pages.contactpage);

const attributes = await getAttribute(['seoConfig', 'branding']);
console.log(attributes.seoConfig, attributes.branding);

© 2024 HedraCMS. All rights reserved.