-
Notifications
You must be signed in to change notification settings - Fork 4k
/
media.ts
102 lines (89 loc) · 1.96 KB
/
media.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* External dependencies
*/
import * as fs from 'fs';
/**
* Internal dependencies
*/
import type { RequestUtils } from './index';
interface Media {
id: number;
title: {
raw: string;
rendered: string;
};
source_url: string;
slug: string;
alt_text: string;
caption: { rendered: string };
link: string;
}
/**
* List all media files.
*
* @see https://developer.wordpress.org/rest-api/reference/media/#list-media
* @param this
*/
async function listMedia( this: RequestUtils ) {
const response = await this.rest< Media[] >( {
method: 'GET',
path: '/wp/v2/media',
params: {
per_page: 100,
},
} );
return response;
}
/**
* Upload a media file.
*
* @see https://developer.wordpress.org/rest-api/reference/media/#create-a-media-item
* @param this
* @param filePathOrData The path or data of the file being uploaded.
*/
async function uploadMedia(
this: RequestUtils,
filePathOrData: string | fs.ReadStream
) {
const file =
typeof filePathOrData === 'string'
? fs.createReadStream( filePathOrData )
: filePathOrData;
const response = await this.rest< Media >( {
method: 'POST',
path: '/wp/v2/media',
multipart: {
file,
},
} );
return response;
}
/**
* delete a media file.
*
* @see https://developer.wordpress.org/rest-api/reference/media/#delete-a-media-item
* @param this
* @param mediaId The ID of the media file.
*/
async function deleteMedia( this: RequestUtils, mediaId: number ) {
const response = await this.rest( {
method: 'DELETE',
path: `/wp/v2/media/${ mediaId }`,
params: { force: true },
} );
return response;
}
/**
* delete all media files.
*
* @param this
*/
async function deleteAllMedia( this: RequestUtils ) {
const files = await this.listMedia();
// The media endpoint doesn't support batch request yet.
const responses = await Promise.all(
files.map( ( media ) => this.deleteMedia( media.id ) )
);
return responses;
}
export { listMedia, uploadMedia, deleteMedia, deleteAllMedia };