]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/shared/abstract-command.ts
3ee5cd8655923e50594250743142a163d935ff0c
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / shared / abstract-command.ts
1 import { HttpStatusCode } from '@shared/core-utils'
2 import { makeDeleteRequest, makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrapBody, unwrapText } from '../requests/requests'
3 import { ServerInfo } from '../server/servers'
4
5 export interface OverrideCommandOptions {
6 token?: string
7 expectedStatus?: number
8 }
9
10 interface CommonCommandOptions extends OverrideCommandOptions {
11 path: string
12 defaultExpectedStatus: number
13 }
14
15 interface GetCommandOptions extends CommonCommandOptions {
16 query?: { [ id: string ]: any }
17 contentType?: string
18 accept?: string
19 }
20
21 abstract class AbstractCommand {
22
23 private expectedStatus: HttpStatusCode
24
25 constructor (
26 protected server: ServerInfo
27 ) {
28
29 }
30
31 setServer (server: ServerInfo) {
32 this.server = server
33 }
34
35 setExpectedStatus (status: HttpStatusCode) {
36 this.expectedStatus = status
37 }
38
39 protected getRequestBody <T> (options: GetCommandOptions) {
40 return unwrapBody<T>(this.getRequest(options))
41 }
42
43 protected getRequestText (options: GetCommandOptions) {
44 return unwrapText(this.getRequest(options))
45 }
46
47 protected deleteRequest (options: CommonCommandOptions) {
48 return makeDeleteRequest(this.buildCommonRequestOptions(options))
49 }
50
51 protected putBodyRequest (options: CommonCommandOptions & {
52 fields?: { [ fieldName: string ]: any }
53 }) {
54 const { fields } = options
55
56 return makePutBodyRequest({
57 ...this.buildCommonRequestOptions(options),
58
59 fields
60 })
61 }
62
63 protected postBodyRequest (options: CommonCommandOptions & {
64 fields?: { [ fieldName: string ]: any }
65 }) {
66 const { fields } = options
67
68 return makePostBodyRequest({
69 ...this.buildCommonRequestOptions(options),
70
71 fields
72 })
73 }
74
75 private buildCommonRequestOptions (options: CommonCommandOptions) {
76 const { token, expectedStatus, defaultExpectedStatus, path } = options
77
78 return {
79 url: this.server.url,
80 path,
81 token: token ?? this.server.accessToken,
82 statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus
83 }
84 }
85
86 private getRequest (options: GetCommandOptions) {
87 const { query, contentType, accept } = options
88
89 return makeGetRequest({
90 ...this.buildCommonRequestOptions(options),
91
92 query,
93 contentType,
94 accept
95 })
96 }
97 }
98
99 export {
100 AbstractCommand
101 }