/
index.js
54 lines (45 loc) · 1.18 KB
/
index.js
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
const { createClient } = require('@sanity/client')
const path = require('path')
const fs = require('fs')
module.exports = async (
job,
settings,
{
input,
params,
document,
fieldName,
fieldType,
filename
},
type
) => {
// make a Sanity client
const client = createClient(params)
// find where the asset to be uploaded is stored
var filePath = input || job.output
if (!path.isAbsolute(filePath)) filePath = path.join(job.workpath, filePath)
// discover any existing asset stored in the field
const fields = `{${fieldName}{asset->}}`;
const existing = await client.fetch(`*[_id == \"${document}\"] ${fields}`, {});
// upload the new asset
const uploaded = await client.assets.upload(fieldType,
fs.createReadStream(filePath),
{
filename: filename
})
// patch the new asset into the field
await client.patch(document)
.set({
[fieldName]: {
_type: fieldType,
asset: {
_type: "reference",
_ref: uploaded._id
}
}
})
.commit()
// if there was already an asset in that field - delete it
if (existing[fieldName]) await client.delete(existing[fieldName]._id)
}