使用Node在用户ID的github上创建gist

时间:2014-06-12 06:27:17

标签: javascript node.js github

我正在尝试使用用户ID在github.com上创建一个要点。目前我可以使用node-github模块创建匿名要点。 这是代码

github.gists.create({
    "description": "the description for this gist",
    "public": true,
    "files": {
        "BONE101TEST_2.md": {
            "content": "<html><h1>This is a Test!</h1><b>Hello</b><img src=></html>"
        }
    }
 }, function(err, rest) {
      console.log(rest);
  });

根据github文档“代表用户阅读或撰写要点,需要使用gist OAuth范围。”这将为我提供用户的代币。 但是我如何指定我想要使用用户X创建gist。我正在阅读node-githu documentation但是没有告诉我这个。有什么想法吗?

更新 我可以根据文档创建一个编程令牌。如果create方法没有引用它,仍然不确定如何识别用户的id来创建gist。

github.authorization.create({
    scopes: ["user", "public_repo", "repo", "repo:status", "gist"],
    note: "what this auth is for",
    note_url: "http://url-to-this-auth-app",
    headers: {
        "X-GitHub-OTP": "two-factor-code"
    }
}, function(err, res) {
    if (res.token) {
        //save and use res.token as in the Oauth process above from now on
    }
});

1 个答案:

答案 0 :(得分:0)

在您与我分享的其中一个链接中有答案。只需修改它。 如果有人需要,这就是代码。

http.createServer(function(req, res) {
    var url = Url.parse(req.url);
    var path = url.pathname;
    var query = querystring.parse(url.query);

    if (path == "/" || path.match(/^\/user\/?$/)) {
        // redirect to github if there is no access token
        if (!accessToken) {
            res.writeHead(303, {
                Location: oauth.getAuthorizeUrl({
                    redirect_uri: 'http://localhost:3000/github-callback',
                    scope: "user,repo,gist"
                })
            });
            res.end();
            return;
        }

        // use github API
        github.gists.create({
          "description": "the description for this gist",
          "public": true,
          "files": {
            "TEST_2.md": {
              "content": "<html><h1>This is a Test!</h1><b>Hello</b><img src=></html>"
              }
            }
          }, function(err, rest) {
            console.log(rest);
          });
        return;
    }
    // URL called by github after authenticating
    else if (path.match(/^\/github-callback\/?$/)) {
        // upgrade the code to an access token
        oauth.getOAuthAccessToken(query.code, {}, function (err, access_token, refresh_token) {
            if (err) {
                console.log(err);
                res.writeHead(500);
                res.end(err + "");
                return;
            }

            accessToken = access_token;

            // authenticate github API
            github.authenticate({
                type: "oauth",
                token: accessToken
            });

            //redirect back
            res.writeHead(303, {
                Location: "/"
            });
            res.end();
        });
        return;
    }

    res.writeHead(404);
    res.end("404 - Not found");
}).listen(3000);