New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@gnql/graphql-blocks

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@gnql/graphql-blocks

latest
Source
npmnpm
Version
0.0.0-alpha.6
Version published
Maintainers
1
Created
Source

Legend GraphQL Library

A TypeScript library providing GraphQL operations with model abstractions, Apollo Client middleware, and intelligent caching capabilities.

Installation

bun install

GraphQL Functionality (@src/graphql)

The @src/graphql module provides comprehensive GraphQL data processing and caching capabilities designed to work seamlessly with Apollo Client.

Core Features

🔄 Automatic Entity Caching

  • Entity Identification: Automatically identifies GraphQL entities (objects with __typename and id fields)
  • Circular Reference Handling: Prevents infinite loops when processing interconnected data
  • Lazy Resolution: Uses proxy objects to resolve entity references on-demand
  • Cache Consistency: Maintains referential integrity across all cached entities

🔗 Apollo Client Integration

  • Middleware Support: Seamless integration with Apollo Client's link chain
  • Operation Lifecycle: Hooks for operation start/end events
  • Automatic Processing: Processes all GraphQL responses without additional configuration

🛠️ Flexible Cache Interface

  • Abstract Base Class: GraphQLCacheUpdater for full Apollo integration
  • Simple Interface: Lightweight GraphQLCacheUpdater type for basic operations
  • Custom Implementation: Easy to implement your own caching strategy

API Reference

Apollo Client Middleware

import { createGraphQLCacheLink } from '@gnql/graphql-blocks';
import { ApolloClient, from, createHttpLink } from '@apollo/client';

// Implement your cache
class MyCache extends GraphQLCacheUpdater {
  private cache = new Map<string, any>();

  get(typename: string, id: string | number): any {
    return this.cache.get(`${typename}:${id}`);
  }

  update(typename: string, id: string | number, value: any): void {
    this.cache.set(`${typename}:${id}`, value);
  }
}

// Create Apollo Client with caching middleware
const httpLink = createHttpLink({ uri: '/graphql' });
const cacheLink = createGraphQLCacheLink(new MyCache());

const client = new ApolloClient({
  link: from([cacheLink, httpLink]),
  // ... other config
});

Manual Data Processing

import { readGraphQLData } from '@gnql/graphql-blocks';

// Process GraphQL data manually
const cacheHandler = new MyCacheUpdater();
cacheHandler.rootData = {
  user: { __typename: 'User', id: '1', name: 'John' },
  posts: [
    { 
      __typename: 'Post', 
      id: '1', 
      title: 'Hello', 
      author: { __typename: 'User', id: '1' } // References the same user
    }
  ]
};

const processedData = readGraphQLData(cacheHandler);
// Entities are now cached and cross-references are maintained

Utility Functions

import { isGraphQLEntity, isObject, hasCustomId } from '@gnql/graphql-blocks';

// Check if an object is a GraphQL entity
if (isGraphQLEntity(data)) {
  console.log(`Entity: ${data.__typename} with ID: ${data.id}`);
}

// Type-safe object checking
if (isObject(value)) {
  console.log(value.someProperty); // TypeScript knows this is safe
}

// Custom ID field support
const customIds = new Map([['User', 'userId'], ['Product', 'sku']]);
if (hasCustomId(user, customIds)) {
  console.log('User has custom ID field');
}

Cache Implementation Guide

import { GraphQLCacheUpdater } from '@gnql/graphql-blocks';

class MyCache extends GraphQLCacheUpdater {
  private entities = new Map<string, any>();

  get(typename: string, id: string | number): any {
    return this.entities.get(`${typename}:${id}`);
  }

  update(typename: string, id: string | number, value: any): void {
    const key = `${typename}:${id}`;
    
    if (value === null || value === undefined) {
      // Handle deletion
      this.entities.delete(key);
    } else {
      // Handle insertion/update
      this.entities.set(key, value);
    }
  }

  onOperationStart(operation: Operation): void {
    console.log(`Starting operation: ${operation.operationName}`);
  }

  onOperationEnd(operation: Operation): void {
    console.log(`Completed operation: ${operation.operationName}`);
  }
}

Simple Interface (Lightweight)

import type { GraphQLCacheUpdater } from '@gnql/graphql-blocks';

const simpleCache: GraphQLCacheUpdater = {
  cache: new Map(),
  
  get(typename: string, id: string | number) {
    return this.cache.get(`${typename}:${id}`);
  },
  
  set(typename: string, id: string | number, value: any) {
    this.cache.set(`${typename}:${id}`, value);
  },
  
  delete(typename: string, id: string | number) {
    this.cache.delete(`${typename}:${id}`);
  }
};

Advanced Features

Circular Reference Handling

The library automatically detects and handles circular references in GraphQL data:

// This data structure with circular references is handled automatically
const data = {
  user: { 
    __typename: 'User', 
    id: '1', 
    posts: [
      { 
        __typename: 'Post', 
        id: '1', 
        author: { __typename: 'User', id: '1' } // Circular reference
      }
    ]
  }
};

Custom ID Fields

Support for GraphQL types that use custom ID fields instead of the standard id:

const customIdFields = new Map([
  ['User', 'userId'],
  ['Product', 'sku'],
  ['Order', 'orderNumber']
]);

// The library will recognize these custom ID fields
const product = { __typename: 'Product', sku: 'ABC123', name: 'Widget' };

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import type { 
  GraphQLEntity, 
  GraphQLCacheUpdater, 
  GraphQLDataHandler 
} from '@gnql/graphql-blocks';

// All types are fully typed and documented
const handler: GraphQLDataHandler = (data, updater) => {
  // Process data with full type safety
};

Development

# Run tests
bun test

# Build the library
bun run build

# Development mode
bun run dev

License

This project was created using bun init in bun v1.2.17. Bun is a fast all-in-one JavaScript runtime.



FAQs

Package last updated on 16 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts