Code Monkey home page Code Monkey logo

hyper's Introduction

hyper

Available on ForgeBox Tested With TestBox

A CFML HTTP Builder

Inspiration

Hyper was built after coding several API SDK's for various platforms — S3SDK, cbstripe, and cbgithub, to name a few. I noticed that I spent a lot of time setting up the plumbing for the requests and a wrapper around cfhttp. Each implementation was mostly the same but slightly different. It was additionally frustrating because I really only needed to tweak a few values, usually just the Authorization header. It would be nice to create an HTTP client pre-configured for each of these SDK's. It seemed the perfect fit for a module.

The problem it solves

Hyper exists to provide a fluent builder experience for HTTP requests and responses. It also provides a powerful way to create clients, i.e. Builder objects with pre-configured defaults like a base URL or certain headers.

Requirements

Hyper runs on Adobe ColdFusion 2018+ and Lucee 5+.

ColdBox is not required, but mappings are provided for ColdBox users automatically.

Documentation

You can find all of the documentation for Hyper at https://hyper.ortusbooks.com.

hyper's People

Contributors

aliaspooryorik avatar daemach avatar elpete avatar gpickin avatar jclausen avatar kamasamak avatar michaelborn avatar mordantwastrel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

hyper's Issues

Wirebox mapping not working

I'm unclear on how to use hyper in a CB6 application. I've tried following the docs and it's just not clear. I've set up wirebox like this: https://www.screencast.com/t/U6DOdsUHN6p but get this after a fwreinit: https://www.screencast.com/t/VWo1NYoPBA I'm trying to do this: https://developers.hubspot.com/docs/api/crm/contacts ( List example - python is easiest to map )

How do I configure a hyper instance for use in this model with a base URL, accept header and an apikey query param that gets sent on every request?

And is this the best place to ask for this kind of help?

The Error "Host name may not be empty"

Trying to use the API for this but it is coming as an error

<cfset Application.hyper = new models.HyperRequest()>

Application.hyper.setMethod("POST")
.setUrl('https://demo2.2c2p.com/2C2PFrontEnd/RedirectV3/payment')
.setBody({
version: '8.5',
merchant_id: 'JT04',
currency: '702',
result_url_1: 'http://localhost:8888/hyper/result.cfm',
hash_value: hash_value,
payment_description: 'Test',
order_id : '#Timeformat(now())#',
amount : '000000002500'
}).send();

"Host name may not be empty"

Move makeCFHTTPRequest to a pluggable HttpClient.send() interface

In order to use different HTTP clients like Apache Common's HTTPClient, create an interface and implementation for CFHTTP.

interface name="HyperHttpClient" {
    public HyperResponse function send( required HyperRequest req );
}

This will require some moving around of existing HyperRequest and HyperResponse methods, but should be fairly simple.

Don't include username and password in every request

This is an edge case but a webservice we're using reacts differently depending on whether cfhttp contains a username and password field or not. We discovered this because it was returning 401 unauthorized even though we were not supplying a username and password, but if we made a regular cfhttp request without those two fields, it worked correctly.

Once I can spend a little more time on this I should be able to submit a PR for it, assuming you're OK with removing those arguments from cfhttp if they're blank.

500 Error when using get

With the following code, I get the error below on the most recent version of hyper.

hyper.get( "http://localhost:4000/healthcheck" )

image

The response is not json.

Hello,

Thank you for this fantastic module. I found it a couple of days ago while researching.

The response below is an error message from the Authorize.net API. The API is XML, but they offer JSON support through a translation of JSON elements to XML elements.

I ran into an issue today while testing and want to get your advice.

First, I understand why I am getting the actual error message in the API response. I can fix that. The focus is the special character at the start of the JSON string causing the issue.

I was able to see that there was a special character until I put the code into tryCF

https://trycf.com/gist/3ae99238fce08639be09390b7bfc344b/lucee5?theme=monokai

{"messages":{"resultCode":"Error","message":[{"code":"E00003","text":"The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'userFields' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'transactionType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."}]}}

Once I spotted the special character, I was able to get around it by doing the following:

ret.data = res.getData();      
        ret.json = "";

        if (isJSON(ret.data)){
            ret.json = res.json();
        } else {
            if (left(ret.data,1)!='{') {
                ret.dataClean= removeChars(ret.data,1,1); 
                if (isJSON(ret.dataClean)) {
                    ret.json = deserializeJSON(ret.dataClean);
                }
            }
        }

        ret.isSuccess = res.isSuccess();

That seemed to work for me. Is there a better way to handle it using the current module functions?

Is something like this worthy of consideration for inclusion in this module? If it is, I feel like there would need to be a bit of extra work done in case more than one special character ended up at the beginning or the end.

Thanks,

Randy

Don't change case of headers or query params

Assume if someone adds two different casings of the same param, they meant to.

The flip side is that this can not interact correctly with certain API's due to case-sensitivity.

Add `withCertificateAuthentication` for Client Cert HTTP requests

The HyperRequest currently supports withBasicAuthentication( username, password ) This issue requests a similar convenience method for client certificate authentication. Suggested methd signature:

/**
* Sets the http request variables for certificate authentication
* @certificatePath  The mapped path to the certificate used to authenticate
* @password           The password used to unlock the certificate - optional
**/ 
public function withCertificateAuthentication( 
required string certificatePath,
string password
){}

Add a forwardHeaders option

This would forward on headers if they exist in the CFML request. (getHTTPRequestData( false ).headers)

(We can make that the default value but allow a struct to be passed in.)

// original
hyperClient
    .when( headers.keyExists( "X-Forwarded-For" ), ( req ) => {
        req.withHeaders( { "X-Forwarded-For": headers[ "X-Forwarded-For" ] } );
    } )
    .when( headers.keyExists( "x-cluster-client-ip" ), ( req ) => {
        req.withHeaders( { "x-cluster-client-ip": headers[ "x-cluster-client-ip" ] } );
    } )
    .post( "/api/v1/login", {
        "username": FORM.user,
        "password": FORM.pass,
        "rememberMe": rememberMe
    } );

becomes

// improved
hyperClient
    .forwardHeaders( [ "X-Forwarded-For", "X-Cluster-Client-IP" ] )
    .post( "/api/v1/login", {
        "username": FORM.user,
        "password": FORM.pass,
        "rememberMe": rememberMe
    } );

forwardHeaders would have a function signature that looks something like this:

public HyperRequest function forwardHeaders(
    required array names,
    struct headers = getHTTPRequestData( false ).headers
)

Additionally, this should be configurable at a client level. The property would probably be forwardedHeaders.

Hyper broken?

I updated to 3.2 and am now getting this error: https://www.screencast.com/t/6rFFbVO8fp

The readme doesn't indicate anything has changed in the DSL. I'm still using property name="hyper" inject="HyperBuilder@Hyper";

I'm trying to troubleshoot cb scheduled tasks - this is the only error I'm seeing, but scheduled tasks no longer work.

Issue when specifying multiple query parameters with the same name

HTTP GET requests allow for multiple parameters to be passed that share the same name. For example, the following GET call to the Twilio lookups API allows for the 'Type' parameter to be specified multiple times.

https://lookups.twilio.com/v1/PhoneNumbers/13056772308?Type=carrier&Type=caller-name

Currently, when calling the setQueryParam or withQueryParams methods on a HyperRequest, the query parameters are stored in a structure, which means multiple parameters with the same name will simply overwrite the previous value.

Instead, parameters should be stored to allow multiple parameters with the same name, similar to how stacking multiple cfhttpparam tags would allow the same parameter name to be used (and passed) multiple times.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.