Skip to content
keypal
Esc
↑↓navigate↵open⌘Jpreview
On this page

ResourceBuilder

Build a key's resources map with a chainable API

ResourceBuilder builds the resources map a key stores: keys are "type:id", values are the scopes granted on that resource. For how resource scopes are checked, see Resource scopes.

import { ResourceBuilder } from 'keypal'

const resources = new ResourceBuilder()
  .add('project', 'proj_1', ['read', 'deploy'])
  .addMany('website', ['site_1', 'site_2'], ['read'])
  .build()
// { 'project:proj_1': ['read', 'deploy'], 'website:site_1': ['read'], 'website:site_2': ['read'] }

await keys.create({ ownerId: 'user_123', resources })

createResourceBuilder() returns new ResourceBuilder().

Methods

Methods that return this can be chained.

Method Returns Does
add(type, id, scopes: string[]) this Grants scopes on type:id, merged with any already there, without duplicates.
addOne(type, id, scope: string) this Same as add with one scope.
addMany(type, ids: string[], scopes: string[]) this add for each id.
remove(type, id) this Removes the resource.
removeScopes(type, id, scopes: string[]) this Removes those scopes; removes the resource when none are left.
has(type, id) boolean Whether the resource has been added.
get(type, id) string[] The resource’s scopes, or [] when it isn’t there.
clear() this Removes every resource.
build() Record<string, string[]> A shallow copy of the map.

ResourceBuilder.from()

static from(resources: Record<string, string[]>): ResourceBuilder

Starts a builder from an existing map, for example to change a stored key’s resources before passing them to rotate().

const record = await keys.findById('key_123')

const resources = ResourceBuilder.from(record?.resources ?? {})
  .add('project', 'proj_2', ['read'])
  .removeScopes('project', 'proj_1', ['deploy'])
  .build()

await keys.rotate('key_123', { resources })

Was this page helpful?