]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/shared/abstract-command.ts
Introduce feed command
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / shared / abstract-command.ts
1 import { HttpStatusCode } from '@shared/core-utils'
2 import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, unwrap, 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 ]: string }
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 putBodyRequest (options: CommonCommandOptions & {
48 fields?: { [ fieldName: string ]: any }
49 }) {
50 const { fields } = options
51
52 return makePutBodyRequest({
53 ...this.buildCommonRequestOptions(options),
54
55 fields
56 })
57 }
58
59 protected postBodyRequest (options: CommonCommandOptions & {
60 fields?: { [ fieldName: string ]: any }
61 }) {
62 const { fields } = options
63
64 return makePostBodyRequest({
65 ...this.buildCommonRequestOptions(options),
66
67 fields
68 })
69 }
70
71 private buildCommonRequestOptions (options: CommonCommandOptions) {
72 const { token, expectedStatus, defaultExpectedStatus, path } = options
73
74 return {
75 url: this.server.url,
76 path,
77 token: token ?? this.server.accessToken,
78 statusCodeExpected: expectedStatus ?? this.expectedStatus ?? defaultExpectedStatus
79 }
80 }
81
82 private getRequest (options: GetCommandOptions) {
83 const { query, contentType, accept } = options
84
85 return makeGetRequest({
86 ...this.buildCommonRequestOptions(options),
87
88 query,
89 contentType,
90 accept
91 })
92 }
93 }
94
95 export {
96 AbstractCommand
97 }