Skip to content

Commit 3b2ff09

Browse files
committed
feat(jike-client): add serialize
1 parent 11b7c1d commit 3b2ff09

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/client/client.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,10 @@ export class JikeClient {
154154
return new JikeUser<M>(this, username)
155155
}
156156

157+
/**
158+
* 获取自身用户
159+
* @returns {@link JikeUser} 实例
160+
*/
157161
getSelf() {
158162
return new JikeUser<true>(this, undefined)
159163
}
@@ -187,6 +191,9 @@ export class JikeClient {
187191
)
188192
}
189193

194+
/**
195+
* 刷新 access token
196+
*/
190197
async renewToken() {
191198
if (!this.#refreshToken)
192199
throw new Error('登录状态已失效,请重新获取 access-token!')
@@ -202,4 +209,45 @@ export class JikeClient {
202209
result.data[`x-${this.#config.endpointId}-refresh-token`]
203210
this.accessToken = result.data[`x-${this.#config.endpointId}-access-token`]
204211
}
212+
213+
/**
214+
* 转换为 JSON 数据
215+
*/
216+
async toJSON(): Promise<JikeClientJSON> {
217+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
218+
const { beforeRetry, ...config } = this.#config
219+
const profile = await this.getSelf().queryProfile()
220+
return {
221+
...config,
222+
accessToken: this.accessToken,
223+
refreshToken: this.refreshToken,
224+
userId: profile.user.id,
225+
username: profile.user.username,
226+
screenName: profile.user.screenName,
227+
}
228+
}
229+
230+
/**
231+
* 序列化
232+
* @param space 缩进空格数
233+
*/
234+
async serialize(space = 0): Promise<string> {
235+
return JSON.stringify(await this.toJSON(), undefined, space)
236+
}
237+
238+
/**
239+
* 反序列化
240+
* @param data 数据
241+
*/
242+
static deserialize(data: string): JikeClient {
243+
const json: JikeClientJSON = JSON.parse(data)
244+
return new JikeClient({ ...json })
245+
}
246+
}
247+
248+
export interface JikeClientJSON extends Omit<ApiConfigResolved, 'beforeRetry'> {
249+
refreshToken: string
250+
userId: string
251+
username: string
252+
screenName: string
205253
}

0 commit comments

Comments
 (0)