@@ -27,7 +27,9 @@ npm i xid-ts --save
2727
2828## Examples
2929
30- ``` js
30+ ### Create and Parse Xid
31+
32+ ``` ts
3133import { Xid } from ' xid-ts'
3234
3335const defaultXid = Xid .default ()
@@ -51,7 +53,7 @@ assert.equal(xid.equals(Xid.fromValue(Buffer.from([77, 136, 225, 91, 96, 244, 13
5153assert .equal (xid .equals (Xid .fromValue (new Uint8Array ([77 , 136 , 225 , 91 , 96 , 244 , 134 , 228 , 40 , 65 , 45 , 201 ]))), true )
5254```
5355
54- ## Encode & Decode With JSON and CBOR
56+ ### Encode & Decode With JSON and CBOR
5557
5658https://github.com/yiwen-ai/xid-ts/blob/main/src/index.test.ts#L70
5759
@@ -78,6 +80,35 @@ const obj2 = decode(data)
7880assert .isTrue (xid .equals (Xid .fromValue (obj2 .id )))
7981```
8082
83+ ### Cloudflare Workers
84+
85+ ``` ts
86+ import { DurableObject } from " cloudflare:workers"
87+ import { Xid , newState , type XidState } from ' xid-ts'
88+
89+ export class GlobalState extends DurableObject {
90+ #xidState: XidState = newState ()
91+
92+ constructor (ctx : DurableObjectState , env : Env ) {
93+ super (ctx , env )
94+ }
95+
96+ xid(): Xid {
97+ return new Xid (undefined , this .#xidState )
98+ }
99+ }
100+
101+ export default {
102+ async fetch(request , env , ctx ): Promise <Response > {
103+ const stub = env .GLOBAL_STATE .getByName (" global" )
104+ // _id is not Xid instance because it comes from DurableObject RPC serialization
105+ const _id = await stub .xid ()
106+ const id = new Xid (_id )
107+ return new Response (JSON .stringify ({id }), { status: 200 })
108+ // {"id":"d4amdocsodcmnao0bddg"}
109+ },
110+ } satisfies ExportedHandler <Env >
111+ ```
81112
82113[ `xid` ] : https://github.com/rs/xid
83114[ object-id ] : https://docs.mongodb.org/manual/reference/object-id/
0 commit comments