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