-
Notifications
You must be signed in to change notification settings - Fork 0
/
entity_files.ts
245 lines (227 loc) · 7.74 KB
/
entity_files.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { assert } from '@std/assert'
import type { AxiosInstance } from 'axios'
import { fileFrom } from 'fetch-blob/from.js'
import type { Readable } from 'node:stream'
import { defaultTransformers } from './axios_default_transformers.ts'
import { createSearchIteratorFn } from './create_search_iterator_fn.ts'
import { EntityRequestFilter } from './field_value_changes.ts'
import type { PagedRequest } from './paged_request.ts'
import type { PagedResponse } from './paged_response.ts'
import type { DateTime, Replace, RequireOnlyOne } from './types.ts'
import { entityFilesUrl } from './urls.ts'
export type { DateTime } from './types.ts'
export type EntityFileRaw = {
/** The unique identifier of the entity file object. */
id: number
/** The name of the file. */
name: string
/** The size of the file in bytes. */
size: number
/** The unique identifier of the person corresponding to the entity file. */
person_id: number | null
/** The unique identifier of the organization corresponding to the entity file. */
organization_id: number | null
/** The unique identifier of the opportunity corresponding to the entity file. */
opportunity_id: number | null
/** The unique identifier of the user who created the entity file. */
uploader_id: number
/** The time when the entity file was created. */
created_at: DateTime
}
export type EntityFile = Replace<EntityFileRaw, {
created_at: Date
}>
/**
* Represents the request parameters for retrieving entity files.
*/
export type AllEntityFileRequest =
| PagedRequest
| (
& RequireOnlyOne<{
/**
* A unique ID that represents a Person whose associated files should be retrieved.
*/
person_id?: number
/**
* A unique ID that represents an Organization whose associated files should be retrieved.
*/
organization_id?: number
/**
* A unique ID that represents an Opportunity whose associated files should be retrieved.
*/
opportunity_id?: number
}>
& PagedRequest
)
export type PagedEntityFileResponseRaw =
& {
entity_files: EntityFileRaw[]
}
& PagedResponse
export type PagedEntityFileResponse = Replace<PagedEntityFileResponseRaw, {
entity_files: EntityFile[]
}>
export type SupportedFileType = File | string
export type UploadEntityFileRequest =
& {
files: SupportedFileType[]
}
& RequireOnlyOne<EntityRequestFilter>
/**
* Entity files are files uploaded to a relevant entity.
* Possible files, for example, would be a pitch deck for an opportunity or a physical mail correspondence for a person.
*/
export class EntityFiles {
/** @hidden */
constructor(private readonly axios: AxiosInstance) {
}
private static transformEntityFile(file: EntityFileRaw): EntityFile {
return {
...file,
created_at: new Date(file.created_at),
}
}
/**
* Returns all entity files within your organization.
*/
async all(params?: AllEntityFileRequest): Promise<PagedEntityFileResponse> {
const response = await this.axios.get<PagedEntityFileResponse>(
entityFilesUrl(),
{
params,
transformResponse: [
...defaultTransformers(),
(json: PagedEntityFileResponseRaw) => {
return {
...json,
entity_files: json.entity_files.map(
EntityFiles.transformEntityFile,
),
}
},
],
},
)
return response.data
}
/**
* Returns an async iterator that yields all entity files matching the given request
* Each yielded array contains up to the number specified in {@link AllEntityFileRequest.page_size} of entity files.
* Use this method if you want to process the entity files in a streaming fashion.
*
* *Please note:* the yielded entity files array may be empty on the last page.
*
* @example
* ```typescript
* let page = 0
* for await (const entries of affinity.entityFiles.pagedIterator({
* person_id: 123,
* page_size: 10
* })) {
* console.log(`Page ${++page} of entries:`, entries)
* }
* ```
*/
pagedIterator = createSearchIteratorFn(
this.all.bind(this),
'entity_files',
)
/**
* Fetches an entity with a specified `entity_file_id`.
*/
async get(entity_file_id: EntityFile['id']): Promise<EntityFile> {
const response = await this.axios.get<EntityFile>(
entityFilesUrl(entity_file_id),
{
transformResponse: [
...defaultTransformers(),
EntityFiles.transformEntityFile,
],
},
)
return response.data
}
/**
* Downloads the entity file with the specified `entity_file_id`.
*
* @example
* ```typescript
* import { promises as fsPromises } from 'node:fs';
* const fileResponseStream = affinity.entityFiles.download(123);
* await fsPromises.writeFile(filePath, fileResponseStream);
* ```
*/
async download(entity_file_id: EntityFile['id']): Promise<Readable> {
const response = await this.axios.get(
entityFilesUrl(entity_file_id, true),
{
responseType: 'stream',
// The download location of entity files is provided via a redirect from Affinity
maxRedirects: 5,
},
)
return response.data
}
/**
* Uploads files attached to the entity with the given id.
*
* The file will display on the entity's profile, provided that the entity is not a person internal to the user's organization.
*
* @example
* ```typescript
* const entityFile = await affinity.entityFiles.upload({
* files: ['/path/to/example.pdf'],
* person_id: 123,
* });
* ```
*/
async upload(params: UploadEntityFileRequest): Promise<boolean> {
const formData = new FormData()
const { files } = params
assert(files.length, 'At least one file must be provided')
if (params.person_id) {
formData.append('person_id', params.person_id.toString())
} else if (params.organization_id) {
formData.append(
'organization_id',
params.organization_id.toString(),
)
} else if (params.opportunity_id) {
formData.append('opportunity_id', params.opportunity_id.toString())
} else {
throw new Error(
'One of person_id, organization_id or opportunity_id must be provided',
)
}
await Promise.all(
files.map((file) => appendToFormData(formData, file)),
)
const response = await this.axios.post<{ success: boolean }>(
entityFilesUrl(),
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
)
return response.data.success === true
}
}
function isFile(file: unknown): file is File {
return file instanceof File
}
async function appendToFormData(
formData: FormData,
file: SupportedFileType,
) {
if (typeof file === 'string') {
const f = await fileFrom(file)
formData.append('files[]', f)
} else if (isFile(file)) {
formData.append('files[]', file)
return null
} else {
throw new Error('Unsupported file type')
}
}