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

hashnode-node-sdk

v3.0.0

Published

A javascript sdk for working with hasnode graphql api

Downloads

587

Readme

Hashnode Node.js SDK

A powerful and flexible Node.js SDK for interacting with the Hashnode GraphQL API. This SDK provides comprehensive access to Hashnode's features including user management, publications, posts, documentation projects, and more.

Table of Contents

Installation

Using npm:

npm install hashnode-node-sdk

Using yarn:

yarn add hashnode-node-sdk

Requirements

  • Node.js 14.x or higher
  • A Hashnode API key

Getting Started

Authentication

import { HashnodeSDKClient } from 'hashnode-node-sdk';

const client = new HashnodeSDKClient({
  apiKey: 'YOUR_API_KEY',
  baseUrl: 'https://gql.hashnode.com', // Optional
});

Basic Setup

The SDK provides several managers for different API functionalities:

  • UserManager - User operations
  • MeManager - Authenticated user operations
  • PostManager - Blog post operations
  • PublicationManager - Publication management
  • DocumentationProjectManager - Documentation management
  • DomainAvailabilityManager - Domain checks
  • MiscellaneousManager - Utility operations

Quick Example

// Fetch user details
const user = await client.userManager.getUser('username');

// Get authenticated user's posts
const myPosts = await client.meManager.getMyPosts(
  10,
  null,
  {},
  'DATE_PUBLISHED_DESC',
);

// Check domain availability
const isAvailable =
  await client.domainAvailabilityManager.checkSubdomainAvailability('myblog');

Core Concepts

Client Structure

The SDK is built around the HashnodeSDKClient class, which provides access to various managers:

const client = new HashnodeSDKClient({
  apiKey: 'YOUR_API_KEY',
});

// Access different managers
client.userManager;
client.meManager;
client.postManager;
client.publicationManager;
client.documentationProjectManager;
client.domainAvailabilityManager;
client.miscManager;

I'll continue creating the detailed README.md, focusing on the API Reference section and beyond:

API Reference

HashnodeSDKClient

The main client class that provides access to all SDK functionality.

const client = new HashnodeSDKClient({
  apiKey: 'YOUR_API_KEY',
  baseUrl: 'https://gql.hashnode.com', // Optional
});

Managers

UserManager

Handles user-related operations.

// Get user details
const user = await client.userManager.getUser('username');

// Get user followers
const followers = await client.userManager.getUserFollowers('username', 1, 10);

// Get user's tech stack
const techStack = await client.userManager.getUserTechStack('username', 1, 10);

MeManager

Handles authenticated user operations.

// Get authenticated user details
const me = await client.meManager.getMe();

// Get email preferences
const preferences = await client.meManager.getMyEmailNotificationPreferences();

// Get personal posts
const myPosts = await client.meManager.getMyPosts(10, null, {});

PostManager

Handles blog post operations.

// Get post by ID
const post = await client.postManager.getPost('postId');

// Get post comments
const comments = await client.postManager.getPostComments(
  'postId',
  10,
  null,
  'RECENT',
);

// Get post likers
const likers = await client.postManager.getPostLikers('postId', 10, null, {});

PublicationManager

Handles publication operations.

// Get publication details
const publication = await client.publicationManager.getPublication('pubId');

// Get publication posts
const posts = await client.publicationManager.getPublicationPostsViaPage(
  'pubId',
  'host',
  10,
  null,
  {},
);

DocumentationProjectManager

Handles documentation project operations.

// Get project details
const project =
  await client.documentationProjectManager.getDocumentationProject(
    'projectId',
    'host',
  );

// Get project guides
const guides =
  await client.documentationProjectManager.getDocumentationProjectGuides(
    'projectId',
  );

DomainAvailabilityManager

Handles domain availability checks.

// Check subdomain availability
const isAvailable =
  await client.domainAvailabilityManager.checkSubdomainAvailability('myblog');

// Check custom domain
const isDomainAvailable =
  await client.domainAvailabilityManager.checkCustomDomainAvailability({
    domain: 'example.com',
  });

Advanced Topics

Error Handling

The SDK provides comprehensive error handling:

try {
  const user = await client.userManager.getUser('username');
} catch (error) {
  if (error.code === 'UNAUTHENTICATED') {
    // Handle authentication error
  } else if (error.code === 'NOT_FOUND') {
    // Handle not found error
  }
}

Pagination

Most list operations support cursor-based pagination:

const posts = await client.postManager.getPostComments(
  'postId',
  10, // first: number of items
  null, // after: cursor for next page
  'RECENT', // Sort order
);

TypeScript Support

The SDK is built with TypeScript and provides comprehensive type definitions:

// Complete type definitions for:
- Client configuration
- API responses
- Manager methods
- Error types
- Pagination parameters

Rate Limiting

The SDK respects Hashnode's API rate limits. Query users are allowed to send up to 20k requests per minute. While Mutations users can send up to 500 requests per per minute.

  • Error Code: TOO_MANY_REQUESTS
  • Handling:
    try {
      await client.userManager.getUser('username');
    } catch (error) {
      if (error.extensions?.code === 'TOO_MANY_REQUESTS') {
        // Handle rate limiting
      }
    }

Error Handling Strategies

The SDK provides structured error handling:

// Error types available
type GqlErrorCode =
  | 'UNAUTHENTICATED'
  | 'FORBIDDEN'
  | 'BAD_USER_INPUT'
  | 'INTERNAL_SERVER_ERROR'
  | 'NOT_FOUND'
  | 'TOO_MANY_REQUESTS';

// Error handling example
try {
  const result = await client.meManager.getMe();
} catch (error) {
  switch (error.extensions?.code) {
    case 'UNAUTHENTICATED':
      // Handle authentication error
      break;
    case 'NOT_FOUND':
      // Handle not found error
      break;
    default:
    // Handle other errors
  }
}

Roadmap

I am actively working on mutations

  • [x] Queries
  • [x] Error Types
  • [x] Manager Adapter
  • [ ] Mutations
  • [ ] Testing

Contributing

Development Setup

  1. Clone the repository:
git clone https://github.com/valentinesamuel/hashnode-node-sdk.git
cd hashnode-node-sdk
  1. Install dependencies:
npm install
  1. Build the project:
npm run build

Code Style

  • Uses Prettier
  • TypeScript strict mode enabled
  • Follow existing code patterns
  • Document all methods with JSDoc comments

Testing

Run tests using:

npm test        # Run all tests
npm run test:watch  # Run tests in watch mode

Pull Request Process

  1. Fork the repository
  2. Create a feature branch
  3. Commit changes
  4. Add tests
  5. Update documentation
  6. Submit PR with detailed description

Troubleshooting

Common Issues

  1. Authentication Errors
// Ensure API key is set correctly
const client = new HashnodeSDKClient({
  apiKey: 'YOUR_API_KEY', // Check API key is valid
});
  1. Rate Limiting
  • Implement exponential backoff
  • Cache frequently accessed data
  • Monitor request limits
  1. Network Issues
  • Check API endpoint accessibility
  • Verify network connectivity
  • Review firewall settings

Debug Tips

  1. Enable debug logging:
const client = new HashnodeSDKClient({
  apiKey: 'YOUR_API_KEY',
  // debug: true // Enable detailed logging
});
  1. Check response data:
try {
  const result = await client.userManager.getUser('username');
  console.log('Response:', JSON.stringify(result, null, 2));
} catch (error) {
  console.error('Error details:', error);
}

Known Limitations

  • Rate limiting constraints
  • API endpoint-specific limitations

Additional Resources

API Documentation

Changelog

See CHANGELOG.md for version history and updates.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support