|
| 1 | +const crypto = require ('crypto-hash') |
| 2 | +const stream = require('stream') |
| 3 | +require('dotenv').config() |
| 4 | + |
| 5 | +const NetlifyAPI = require('netlify') |
| 6 | +const client = new NetlifyAPI(process.env.NETLIFY_API_TOKEN) |
| 7 | +const site_id = 'b8d481fc-f70c-45f8-9242-3936c27fe7e6' |
| 8 | + |
| 9 | +const uploadFile = async ({ deployId, path, buffer }) => { |
| 10 | + const bufferStream = new stream.PassThrough() |
| 11 | + bufferStream.end(buffer) |
| 12 | + |
| 13 | + const result = await client.uploadDeployFile({ |
| 14 | + deployId, |
| 15 | + path, |
| 16 | + body: bufferStream, |
| 17 | + }) |
| 18 | + |
| 19 | + return result |
| 20 | +} |
| 21 | + |
| 22 | +const upload = async () => { |
| 23 | + let files = [] |
| 24 | + try { |
| 25 | + files = await client.listSiteFiles({ site_id }) |
| 26 | + } catch (e) { |
| 27 | + console.log(e.json) |
| 28 | + } |
| 29 | + |
| 30 | + let existingFiles = {} |
| 31 | + files.forEach(({ path, sha }) => { |
| 32 | + existingFiles[`${path}`] = sha |
| 33 | + }) |
| 34 | + |
| 35 | + const now = new Date() |
| 36 | + const newFileBuf = Buffer.from(now.toISOString()) |
| 37 | + |
| 38 | + const sha = await crypto.sha1(newFileBuf) |
| 39 | + const key = `/static/${sha}/now.txt` |
| 40 | + const newFile = {} |
| 41 | + newFile[key] = sha |
| 42 | + let deploy = [] |
| 43 | + try { |
| 44 | + deploy = await client.createSiteDeploy({ |
| 45 | + site_id, |
| 46 | + body: { |
| 47 | + files: { |
| 48 | + ...existingFiles, |
| 49 | + ...newFile |
| 50 | + } |
| 51 | + } |
| 52 | + }) |
| 53 | + } catch (e) { |
| 54 | + console.log(e.json) |
| 55 | + } |
| 56 | + |
| 57 | + const { id: deployId, required } = deploy |
| 58 | + if( required.length === 0 ) { |
| 59 | + console.log('nothing to upload (1)') |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + if (!required.includes(sha)) { |
| 64 | + console.log('nothing to upload (2)') |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + const uploadList = [{ |
| 69 | + deployId, |
| 70 | + path: key, |
| 71 | + buffer: newFileBuf |
| 72 | + }] |
| 73 | + console.log(uploadList) |
| 74 | + |
| 75 | + result = await Promise.all( |
| 76 | + uploadList.map(item => uploadFile(item)) |
| 77 | + ) |
| 78 | + console.log('Why are all fields capitalized?') |
| 79 | + console.log(result) |
| 80 | + |
| 81 | +} |
| 82 | + |
| 83 | +upload() |
0 commit comments