1.0.0 • Published 10 months ago

sfcc-requests v1.0.0

Weekly downloads
-
License
Unlicense
Repository
github
Last release
10 months ago

SFCC Requests

This project is an easy way to make requests in salesforce commerce cloud.

Usage Flow

  • Each BM Service must have an endpoint
  • RequestService; loads and handle the BM Service
  • RequestBuilder; encapsulates the core methods for creating a request

Installation

Download the folder requests and put in your cartridge, I recommend put the requests folder inside the scripts folder


Request Service

The RequestService is the first layer of a request

const RequestService = require('*/cartridge/<my-cartridge>/scripts/requests/RequestService.js')

const myService = new RequestService("my-service");
if (myService.hasError) { // Check if service has any error
    var err = myService.error // Get the service error message
    // ...
}
// ...

A RequestService instance allows you to call a http method, it returns a RequestBuilder instance

Supported HTTP Methods:

  • GET
  • POST
  • PATCH
  • PUT
  • DELETE

RequestBuilder

The RequestBuilder is the second layer of the request process

const myService = new RequestService("my-service");
if (myService.hasError) { // Check if service has any error
    var err = myService.error // Get the service error message
    // ...
}

myService.GET("your-endpoint")      // Use this method to create a GET request
myService.POST("your-endpoint")     // Use this method to create a POST request
myService.PATCH("your-endpoint")    // Use this method to create a PATCH request
myService.PUT("your-endpoint")      // Use this method to create a PUT request
myService.DELETE("your-endpoint")   // Use this method to create a DELETE request

About the request final URL

The request URL is Service URL + Endpoint

Example, your service contains the url https://localhost/ and you call a GET request to users

The result is https://localhost/users

Very simple example of a get Request

const myService = new RequestService("my-service");
if (myService.hasError) { // Check if service has any error
    var err = myService.error // Get the service error message
    // ...
}

const request = myService.GET("your-endpoint")
const response = request.call() // This method performs the request


var status = response.status // Response status
var body = response.body // Response body
var headers = response.headers // Response headers

Request Builder Methods

Getting information about the request

/**
 * @type {RequestBuilder}
 */
const request = myService.GET("your-endpoint")

// Returns the current URL
request.getURL()

// Returns the current Headers
request.getHeaders()

// Returns the current body
request.getBody()

// Returns the current url query params
request.getQueryParams()

// Returns the current form multiparts (Use it to form)
request.getMultiParts()

Setting Headers

// Add a header to request headers
request.addHeader('Header', 'Value')

// Or

// Add many headers to request headers
request.setHeaders({
    'Header_1': 'Value_1',
    'Header_2': 'Value_2'
})

Setting Body

Raw Body
// Set a request body
//      The first argument is a string (raw body)
//      The second argument is the Content-Type 
request.setBody("payload", "text/plain")
JSON Body
// Set a JSON in the request body and add the header Content-Type as application/json
request.setJSON({"first_name": "John", "last_name": "Doe"})
Working with Forms
// To create a form, use the addMultiPart
const HTTPRequestPart = require('dw/net/HTTPRequestPart')

// Each addMultiPart adds a form field in the current request body
request.addMultiPart(new HTTPRequestPart("first_name", "John")) // field_name and field_value
request.addMultiPart(new HTTPRequestPart("last_name", "Doe"))

Setting Query Params

// Add the query param to current query params
request.addQueryParam("sort", "desc")

// You can verify the current url using the method `request.getURL()` 
// Example of updated url = https://localhost/users?sort=desc

Call function Options

The call function, performs the HTTP request, it has some options.

OptionValueDescription
sendAsMultiPartbooleanCase true, then sends the body as a multipart form
followRedirectbooleanCase true, then follow a HTTP redirect
parseResponsebooleanCase true, then executes the JSON.parse in the response body
timeoutnumberThe number of milliseconds to wait for a response (the maximum is 15 minutes)

Example of a request using options

var response = myRequest.call({
    followRedirect: true, // Follows a HTTP Redirect
    parseResponse: true, // Parse the response body
})

Request Content Types

This is an internal helper for creating the Content-Type header

This can be useful to standardize headers, it is inspired by the MediaType class of spring boot

Most MIME types can be found in this helper

Usage

Application JSON

const RequestContentTypes = require('*/cartridge/<my-cartridge>/scripts/requests/internal/RequestContentTypes.js')

var json = RequestContentTypes.JSON().getValue() // Returns application/json
// or
var jsonEncode = RequestContentTypes.JSON().getValueEncoded("UTF-8") // Returns application/json; charset: UTF-8

Any, Other Types and Custom Mime

RequestContentTypes.ANY_TYPE().getValue()       // Returns */*
RequestContentTypes.OCTET_STREAM().getValue()   // Returns application/octet-stream
RequestContentTypes.PLAIN_TEXT().getValue()     // Returns text/plain

// Or, create a custom MIME

RequestContentTypes.CUSTOM("aaa", "bbb").getValue() // Returns aaa/bbb

Predefined MIME types supported

NAMECONTENT-TYPE
ANY_TYPE*/*
ANY_TEXT_TYPEtext/*
ANY_IMAGE_TYPEimage/*
ANY_AUDIO_TYPEaudio/*
ANY_VIDEO_TYPEvideo/*
ANY_APPLICATION_TYPEapplication/*
CACHE_MANIFESTtext/cache-manifest
CSStext/css
CSVtext/csv
HTMLtext/html
I_CALENDARtext/calendar
PLAIN_TEXTtext/plain
TEXT_JAVASCRIPTtext/javascript
TSVtext/tab-separated-values
VCARDtext/vcard
WMLtext/vnd.wap.wml
XMLtext/xml
BMPimage/bmp
CRWimage/x-canon-crw
GIFimage/gif
ICOimage/vnd.microsoft.icon
JPEGimage/jpeg
PNGimage/png
PSDimage/vnd.adobe.photoshop
SVGimage/svg+xml
TIFFimage/tiff
WEBPimage/webp
MP4_AUDIOaudio/mp4
MPEG_AUDIOaudio/mpeg
OGG_AUDIOaudio/ogg
WEBM_AUDIOaudio/webm
MP4_VIDEOvideo/mp4
MPEG_VIDEOvideo/mpeg
OGG_VIDEOvideo/ogg
QUICKTIMEvideo/quicktime
WEBM_VIDEOvideo/webm
WMVvideo/x-ms-wmv
APPLICATION_XMLapplication/xml
ATOMapplication/atom+xml
BZIP2application/x-bzip2
DARTapplication/dart
APPLE_PASSBOOKapplication/vnd.apple.pkpass
EOTapplication/vnd.ms-fontobject
EPUBapplication/epub+zip
FORM_DATAapplication/x-www-form-urlencoded
KEY_ARCHIVEapplication/pkcs12
APPLICATION_BINARYapplication/binary
GZIPapplication/x-gzip
JAVASCRIPTapplication/javascript
JSONapplication/json
MANIFEST_JSONapplication/manifest+json
KMLapplication/vnd.google-earth.kml+xml
KMZapplication/vnd.google-earth.kmz
MBOXapplication/mbox
APPLE_MOBILE_CONFIGapplication/x-apple-aspen-config
MICROSOFT_EXCELapplication/vnd.ms-excel
MICROSOFT_POWERPOINTapplication/vnd.ms-powerpoint
MICROSOFT_WORDapplication/msword
OCTET_STREAMapplication/octet-stream
OGG_CONTAINERapplication/ogg
OOXML_DOCUMENTapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
OOXML_PRESENTATIONapplication/vnd.openxmlformats-officedocument.presentationml.presentation
OOXML_SHEETapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
OPENDOCUMENT_GRAPHICSapplication/vnd.oasis.opendocument.graphics
OPENDOCUMENT_PRESENTATIONapplication/vnd.oasis.opendocument.presentation
OPENDOCUMENT_SPREADSHEETapplication/vnd.oasis.opendocument.spreadsheet
OPENDOCUMENT_TEXTapplication/vnd.oasis.opendocument.text
PDFapplication/pdf
POSTSCRIPTapplication/postscript
PROTOBUFapplication/protobuf
RDF_XMLapplication/rdf+xml
RTFapplication/rtf
SFNTapplication/font-sfnt
SHOCKWAVE_FLASHapplication/x-shockwave-flash
SKETCHUPapplication/vnd.sketchup.skp
TARapplication/x-tar
WOFFapplication/font-woff
XHTMLapplication/xhtml+xml
XRDapplication/xrd+xml
ZIPapplication/zip