Search code examples
javascriptjelastic

Try to execute js script in manifest to ask privatte API with post request


I try to use js script in my jps to test credentials with a personal APi. The idea is to return an error code in the jps if credentials are false. In my computer my js script works fine but when i try to start my jps with this i have an javascript error.

my jps:

onInstall:

- script [*]: https://github.com/user/project/blob/master/script.js responses: 401: type: error message: bad credentials

My js script:


    const https = require('https')


    var name = "some-name"
    var password = "some-password"```



    const data = JSON.stringify({
      "auth": {
          "identity": {
              "methods": [
                  "password"
              ],
              "password": {
                  "user": {
                      "domain": {
                          "id": "default"
                      },
                      "name": name,
                      "password": password
                  }
              }
          },
          "scope": {
              "project": {
                  "domain": {
                      "id": "default"
                  },
                  "name": "some-name"
              }
          }
      }
    })
    const options = {
      hostname: 'mYapi.com',
      port: 443,
      path: 'mypath',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
      }
    }

    var req = https.request(options, (res) => {
      console.log(`statusCode: ${res.statusCode}`)
      console.log(res.statusCode)
      return res.statusCode;

    })

    req.on('error', (error) => {
      console.error(error)

    })

    req.write(data)
    req.end()


I get this error in the console :

ERROR: script.response: {"result":1704,"line":50,"response":null,"source":"hx-core","time":122,"error":"org.mozilla.javascript.EvaluatorException: syntax error"}

And i try a lot of differents script to do this post request ----> works in my computer ( api send result 201 if credentials are good and 401 if not ) , -----> doesn't work in jelastic manifest.

So please can you explain me how i can do a post request with json on my API in Jelastic manifest ( js call script ). I thank you in advance !


Solution

  • The code that is executed by the "script" action runs on the JVM therefore it allows you to connect and use Java libraries. To implement a POST request and determine the status of the output code, you can use Commons HttpClient. See below for an example.

    type: install
    name: HttpClient Post
    
    onInstall:
    - script: |
        import org.apache.commons.httpclient.HttpClient;
        import org.apache.commons.httpclient.HttpStatus;
        import org.apache.commons.httpclient.methods.PostMethod;
        import org.apache.commons.httpclient.methods.StringRequestEntity;
    
        var client = new HttpClient();
    
        var name = "some-name";
        var password = "some-password";
    
        var requestEntity = new StringRequestEntity(toJSON({
            "auth": {
                "identity": {
                    "methods": [
                        "password"
                    ],
                    "password": {
                        "user": {
                            "domain": {
                                "id": "default"
                            },
                            "name": name,
                            "password": password
                        }
                    }
                },
                "scope": {
                    "project": {
                        "domain": {
                            "id": "default"
                        },
                        "name": "some-name"
                    }
                }
            }
        }), "application/json", "UTF-8");
    
    
        var post = new PostMethod("https://example.com/");
    
        post.setRequestEntity(requestEntity);
    
        var status = client.executeMethod(post);
        post.releaseConnection();
    
        if (status == HttpStatus.SC_CREATED) { // 201
            return { type : "success" };    
        } else if (status == HttpStatus.SC_UNAUTHORIZED) { // 401
            return { type: "error", message: "bad credentials" };
        }
    
        return { type: "error", message: "unknown error" };
    

    Also, you can find many useful examples and information in the Jelastic JPS Collection repository.

    Perhaps the next script will be useful for you: https://github.com/jelastic-jps/git-push-deploy/blob/master/scripts/add-web-hook.cs

    One last thing that if you don't need the exact HTTP Status, you can use an integrated "Transport" class.

    import com.hivext.api.core.utils.Transport;
    
    var name = "some-name";
    var password = "some-password";
    
    var data = toJSON({
      "auth": {
        "identity": {
          "methods": [
            "password"
          ],
          "password": {
            "user": {
              "domain": {
                "id": "default"
              },
              "name": name,
              "password": password
            }
          }
        },
        "scope": {
          "project": {
            "domain": {
              "id": "default"
            },
            "name": "some-name"
          }
        }
      }
    });
    
    try {
        new Transport().post("https://example.com/", data, {
            'Content-Type': 'application/json',
            'Content-Length': data.length
        });    
    
        return { type: "success" };
    } catch (e) {
        return {
            type: "error",
            message: "unknown error: " + e
        };
    }