Created
September 6, 2024 02:59
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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