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

@pallad/entity-ref

v2.1.0

Published

Create small references to entities

Downloads

8

Readme


CircleCI npm version Coverage Status License: MIT

Example code

Helper to create consistent entity references used for uniquely identify entity without all its data.

Especially useful if you need to create an address/reference of any kind of entity in places like:

Use cases

  • audit logs
  • targeting entities in cascade actions for @pallad/cascade
  • targeting in ACL
  • passing entity reference through messaging channels without sending entire entity
  • base for enigmatic IDs

Community

Join our discord server

Installation

npm install @pallad/entity-ref

Usage

The most useful part of this lib is createFactory responsible for creating entity ref, adding extra factories and testing the type.

const userRefFactory = createFactory(
		'user', // indicate type name
		(id: string) => ({id}), // main factory that also describes the shape of entity ref data
);

// create ref for given ID
const ref = userRefFactory('1'); // {type: 'user', data: {id: '1'}}

Testing type

You can check if ref is actually a ref for given type using .is method.

const articleRefFactory = createFactory(
		'article',
		(id: string) => ({id}),
);

const ref = articleRefFactory('1'); // {type: 'article', data: {id: '1'}}

userRefFactory.is(ref) // false
articleRefFactory.is(ref) // true

.is plays a role of type guard as well.

if (articleRefFactory.is(ref)) {
    ref.type // 'article';
	ref.data.id // 👍 typescript knows shape of article refs so no error here
	ref.data.someOtherProperty // ⚠️ this fails
}

Extra factories

Third argument of createFactory accepts an object with extra factories in final factory object.

class Article {
	readonly id: string;
	readonly title: string;
	readonly createdAt: Date;
	readonly updatedAt: Date;
	readonly authorId: string;

	constructor(data: Article) {
		Object.assign(this, data);
	}
}

const articleRefFactory = createFactory(
		'article',
		(id: string) => ({id}),
		{
			fromEntity({id}: Article) {
				return {id}; // note that it has to return the same data as above
			}
		}
);

articleRefFactory('10');
// {type: 'article', data: {id: '10'}}

articleRefFactory.fromEntity(
		new Article({
			id: '10',
			title: 'Example title',
			createdAt: new Date(),
			updatedAt: new Date(),
			authorId: '20'
		})
);
// {type: 'article', data: {id: '10'}}

Hierarchical data

Storing only main id in entity seems to be useless in many scenarious but lets imagine that every article belongs to organization or workspace so it would be nice to return that information in ref as well.

const articleRefFactory = createFactory(
    'article',
    (id: string, workspaceId: string) => ({id, workspaceId}),
    {
        fromEntity({id, workspaceId}: Article) {
            return {id, workspaceId};
        }
    }
);

Examples

Targeting in ACL

import {EntityRef} from "@pallad/entity-ref";

export function hasReadPermission(entityRef: EntityRef<any, any>) {
    if (entityRef.type === 'article') {
        // TODO perform extra checks
    } else if (entityRef.type === 'user') {
        // TODO perform extra checks
    }
    return false;
}

// controller.ts
export default {
    findArticle(id: string) {
        if (!hasReadPermission(articleRefFactory(id))) {
            throw new Error('Insufficient permissions');
        }
        // fetch and return article
    }
}

Audit log

import {EntityRef} from "@pallad/entity-ref";

export function articleCreated(article: Article) {
    return entityCreated(articleRefFactory.fromEntity(article));
}

export function entityCreated(ref: EntityRef<any, any>) {
    return createAuditLog({
        name: 'entity.created',
        ref
    });
}

Enigmatic IDs

import {EntityRef} from "@pallad/entity-ref";

export function decodeId(id: string): EntityRef<any, {id: string}> {
    const [type, id] = Buffer.from(id, 'base64').toString('utf8').split('-');
    return EntityRef.create(type, {id});
}

export function encodeId(ref: EntityRef<any, {id: string}>) {
    return Buffer.from(`${ref.type}-${ref.data.id}`).toString('base64');
}

encodeId(articleRefFactory('1')) // 'YXJ0aWNsZS0x'
decodeId('YXJ0aWNsZS0x') // {type: 'article', data: {id: '1'}}