Skip to content

Instantly share code, notes, and snippets.

@jessekelly881
Created September 6, 2024 02:59
Show Gist options
  • Select an option

  • Save jessekelly881/847d51dc04c3ca98054323d4dc93251a to your computer and use it in GitHub Desktop.

Select an option

Save jessekelly881/847d51dc04c3ca98054323d4dc93251a to your computer and use it in GitHub Desktop.
Encodes a number to a string using `hashids`. Provides a HashedIdConfig Tag to configure salt, etc.
import { Schema } from "@effect/schema";
import { Context, Effect, Option } from "effect";
import Hashids from 'hashids';
// const hashids = new Hashids()
/**
* Configuration for `hashids`. Default is `new Hashids()`.
*
* @since 1.0.0
*/
export class HashedIdConfig extends Context.Tag("HashedIdConfig")<HashedIdConfig, {
salt?: string,
minLength?: number,
alphabet?: string,
seps?: string
}>() {}
/**
* @internal
*/
const hashids = Effect.serviceOption(HashedIdConfig).pipe(
Effect.map(Option.match({
onNone:() => new Hashids(),
onSome: ({ salt, minLength, alphabet, seps }) => new Hashids(salt, minLength, alphabet, seps)
})))
/**
* An id encoded using `hashids`. Uses `HashedIdConfig` to configure the `hashids` instance used.
* Default is `new Hashids()`.
*/
export const HashedId = Schema.transformOrFail(Schema.String, Schema.Number, {
encode: id => hashids.pipe(Effect.map(({ encode }) => encode(id))),
decode: hash => hashids.pipe(Effect.map(({ decode }) => decode(hash)[0] as number))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment