i wrote puuid in typescript

This commit is contained in:
Soph :3 2026-01-04 14:12:17 +02:00
parent 8a2c3d05c9
commit 91284c242a
4 changed files with 100 additions and 45 deletions

View file

@ -1,22 +1,40 @@
import { definePrefix, type Puuid } from "./puuid"
export const UserID = definePrefix("user");
export const GroupID = definePrefix("group");
export const ServerID = definePrefix("srv");
export type UserId = Puuid<"user">;
export type GroupId = Puuid<"group">;
export type ServerId = Puuid<"srv">;
export const Status: Record<string, 1|2|3> = {
OFFLINE: 1,
DND: 2,
ONLINE: 3
}
interface InnerData {
id: string
}
export interface Friend extends InnerData {
export interface User {
id: UserId
name: string,
status: 1|2|3,
image: string
}
export interface Group extends InnerData {
export interface Group {
id: GroupId
name: string
members: number
}
export interface Server extends InnerData {
export interface Server {
id: ServerId
name: string
image: string
}
export interface Data {
friends: User[],
groups: Group[],
servers: Server[],
};

42
src/lib/puuid.ts Normal file
View file

@ -0,0 +1,42 @@
import { v4 as uuidv4 } from "uuid";
import { v7 as uuidv7 } from "uuid";
type Brand<K, T> = K & { __brand: T };
export type Puuid<Prefix extends string> = Brand<
string,
{ prefix: Prefix }
>;
export function definePrefix<const P extends string>(prefix: P) {
const withPrefix = (uuid: string) =>
`${prefix}_${uuid}` as Puuid<P>;
return {
prefix,
is(value: string): value is Puuid<P> {
return value.startsWith(prefix + "_");
},
newV7(): Puuid<P> {
return withPrefix(uuidv7());
},
newV4(): Puuid<P> {
return withPrefix(uuidv4());
},
parse(value: string): Puuid<P> {
if (!value.startsWith(prefix + "_")) {
throw new Error(
`Invalid prefix, expected "${prefix}_"`
);
}
return value as Puuid<P>;
},
inner(id: Puuid<P>): string {
return id.slice(prefix.length + 1);
},
};
}