Making a new gist with dynamic filename?

224 views Asked by At

I'm trying to create a new gist using the below code (everything works except when I try to make the filename dynamic. Every other variable replacement works except for filename. I can't figure out why it's breaking.

var fn = "textfile.txt";
function createGist(token,content,description,shopName,filename){
    $.ajax({ 
        url: 'https://api.github.com/gists',
        type: 'POST',
        beforeSend: function(xhr) { 
            xhr.setRequestHeader("Authorization", "token " + token); 
        },
        data: JSON.stringify({"description": description,"public": false,"files": {fn: {"content": content }}})
    }).done(function(response) {
        console.log(response);
        GM_setValue(shopName,response.id);
    });
}

The filename variable the only part of it that's not working (aka replacing it with the actual string works)

1

There are 1 answers

3
Dan D. On BEST ANSWER

Assuming that fn should be the file name. You need to replace:

"files": {fn: {"content": content }}}

with

"files": files

where

var files = {};
files[filename] = {"content": content};

as keys in object literals can't be the value of a variable. In the old code the file name always ends up being fn.

For clarification here is the whole code with the proposed changes:

var fn = "textfile.txt";
function createGist(token,content,description,shopName,filename){
    var files = {};
    files[filename] = {"content": content};
    $.ajax({ 
        url: 'https://api.github.com/gists',
        type: 'POST',
        beforeSend: function(xhr) { 
            xhr.setRequestHeader("Authorization", "token " + token); 
        },
        data: JSON.stringify({"description": description,"public": false,"files": files})
    }).done(function(response) {
        console.log(response);
        GM_setValue(shopName,response.id);
    });
}