Last active
October 4, 2017 13:50
-
-
Save ihfazhillah/864baac0729fa042cfb27e9688a998d1 to your computer and use it in GitHub Desktop.
My Implementation of netlify assets API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var config = require('./config.json'), | |
fs = require('fs'), | |
request = require('request-promise') | |
let url = `https://api.netlify.com/api/v1/sites/${config.siteid}/assets` | |
let headers = { | |
Authorization : `Bearer ${config.token}` | |
} | |
let getOptions = { | |
headers: headers, | |
url: url, | |
method: "get" | |
} | |
let postOptions = { | |
headers: headers, | |
url: url, | |
method: "post", | |
json: true | |
} | |
// get all assets, logging list of assets | |
request(getOptions).then(data => console.log(data)).catch(err => console.log(err)) | |
/* | |
// use fs.stat to get file size | |
fs.stat('image.png', (err, stat) => { | |
if(stat){ | |
// define the body | |
// first, we request to netlify server with name, size, and content_type part. its all is required. | |
// then, we get a response. in that response, we upload our original file into url specified in response | |
let body = { | |
name: 'image.png', | |
size: stat.size, | |
content_type: 'image/png' | |
} | |
postOptions.body = body | |
request(postOptions).then(data => { | |
// this the uploading file process | |
let formUrl = data.form.url | |
let formFields = data.form.fields | |
let assetId = data.asset.id | |
let assetUrl = data.asset.url | |
const formData = {} | |
Object.keys(formFields).forEach(key => formData[key] = formFields[key]) | |
fs.readFile('image.png', (err, file) => { | |
formData.file = { | |
value: file, | |
options: { | |
filename: 'image.png', | |
contentType: 'image/png' | |
} | |
} | |
request({ | |
url: formUrl, | |
method: 'post', | |
formData: formData | |
}).then(response => console.log(response)).catch(err => console.warn(err)) | |
}); | |
}).catch(err => console.log(err)) | |
} | |
}) | |
*/ | |
/* | |
// delete specific assets | |
request({ | |
headers: headers, | |
url: url + '/59d4ddc4a6188f789548f003', | |
json: true, | |
method: "delete" | |
}).then(data => console.log(data)) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment