MCPcopy Create free account
hub / github.com/Tatamo/atcoder-cli / Session

Class Session

src/session.ts:64–174  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

62 * こいつでcookieを使いまわしてログイン認証した状態でデータをとってくる
63 */
64export class Session implements SessionInterface {
65 private static _axios: import("axios").AxiosInstance | null = null;
66 private CookieConstructor: CookieConstructorInterface
67 private _cookies: CookieInterface | null;
68 private _currentTransaction: Transaction | null = null;
69
70 constructor(CookieConstructor: CookieConstructorInterface) {
71 this.CookieConstructor = CookieConstructor
72 this._cookies = null;
73 }
74
75 // 必要になった瞬間にaxiosをimportする
76 static async importAxios(): Promise<import("axios").AxiosInstance> {
77 if (Session._axios === null) {
78 const _axios = (await import("axios")).default;
79 // 常にtext/htmlをAcceptヘッダーに加えて通信する
80 return Session._axios = _axios.create({headers: {Accept: "text/html"}});
81 }
82 return Session._axios;
83 }
84
85 async getCookies(): Promise<CookieInterface> {
86 if (this._currentTransaction !== null) {
87 // if this is inside a transaction, use the temporal cookie.
88 return this._currentTransaction.cookies;
89 }
90 if (this._cookies === null) {
91 return this._cookies = await this.CookieConstructor.createLoadedInstance();
92 }
93 return this._cookies;
94 }
95
96 async get(url: string, options: AxiosRequestConfig = {}): Promise<SessionResponseInterface> {
97 return this.makeSessionResponse(await (await Session.importAxios())(url, {
98 headers: {
99 Cookie: (await this.getCookies()).get().join("; ")
100 },
101 ...options
102 }))
103 }
104
105 async post(url: string, data?: any, options: AxiosRequestConfig = {}): Promise<SessionResponseInterface> {
106 return this.makeSessionResponse(await (await Session.importAxios()).post(url, data, {
107 headers: {
108 Cookie: (await this.getCookies()).get().join("; ")
109 },
110 ...options
111 }))
112 }
113
114 async transaction<R>(callback: () => Promise<R>): Promise<R> {
115 if (this._currentTransaction !== null) {
116 throw new Error("Cannot start a new transaction inside transaction.")
117 }
118 const currentCookies = await this.getCookies();
119 this._currentTransaction = {
120 cookies: currentCookies.clone(),
121 isUpdated: false

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected