logo
down
shadow

Node.js 'request' module wrapper with optional params - how to write this more concise?


Node.js 'request' module wrapper with optional params - how to write this more concise?

Content Index :

Node.js 'request' module wrapper with optional params - how to write this more concise?
Tag : javascript , By : Johannes
Date : November 24 2020, 09:00 AM

may help you . I'm writing a wrapper around : , For this many parameters, use an options hash.
var RequestWrapper = function(opts) {
    var uri = urljoin(config.baseUrl, opts.type, (typeof opts.uuid === 'string') ? opts.uuid : "")
    var params = request.initParams(uri, {
      body: opts.body
    }, opts.callback)
/* etc */
var RequestWrapper = function(opts) {
    let {client, method, type, uuid = '', body, callback} = opts; // default for uuid
/* etc */

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

What is the right way to write a wrapper module for conditional OO module loading?


Tag : perl , By : DonMac
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Personally I'd go with the first technique. Creating a class that sometimes inherits from one parent, and sometimes inherits from another, seems a little dirty to me. It'll work certainly, but it will confuse class analysis tools (like Pod::Coverage::CountParents) no end.
That said, I'd probably rename sub new to something like new_by_platform. There's a strong expectation that My_Module->new will return an object of type My_Module. Having it return an object of another class could confuse people. (Though if My_Module::Win32 and My_Module::Linux inherit from My_Module, then naming it new seems less bad.)

How to pass optional params when connecting to node.js


Tag : node.js , By : kema
Date : March 29 2020, 07:55 AM
wish of those help if what you want is passing something from the client to the server, you can't do it inside onConnect function.
what you need here is defining a server side function and call it from the client. also your server implementation is wrong.
var express = require('express')
   , app = express(app)
   , server = require('http').createServer(app);
// serve static files from the current directory
app.use(express.static(__dirname));


var Eureca = require('eureca.io');
var eurecaServer = new Eureca.Server();

eurecaServer.exports.init = function(param) {
     //do what you want with param

     //if you want to get the client connection id you can use the code bellow
     var connID = this.socket.id;
}

eurecaServer.attach(server);
//detect client connection
eurecaServer.onConnect(function (conn) {    
   console.log('New Client id=%s ', conn.id, conn.remoteAddress);
})
<head>
  <script src="/eureca.js"></script>
</head>
<body>
<script>

    var eurecaClient = new Eureca.Client();

        eurecaClient.ready(function (serverProxy) {
               serverProxy.init('hello'); //<==== here you call the server side init, and you pass 'hello' as parameter
        });

</script>
</body>

http module (of node.js with browserify) doesn't write request body with method PATCH


Tag : javascript , By : rhinojosa
Date : March 29 2020, 07:55 AM
it helps some times I ended up using the "request" library for node.js. Following code works:
var request = require("request");
(...)

function patch(path, entity){
    var deferred = q.defer();     
    var escapedPath = escapeSpaces(path);
    AuthProvider.retrieveToken().done(function (authToken){
        var headers ={
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0',
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+ authToken,
            'Accept': 'application/json'     
        }

        var options = {
            url: "https://"+resourceApiId+"/api/data/v8.0/"+escapedPath,
            method: 'PATCH',
            headers: {
                'OData-MaxVersion': '4.0',
                "OData-Version": '4.0',
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": 'Bearer '+ authToken,
                "Accept": "application/json"                
            },
            json: entity      
        };  

        request(options, function(error, response, body){
                if (!error) {
                    console.log("patchrequest statuscode: "+response.statusCode )
                    deferred.resolve(true);
                }
                deferred.reject(error);
            }
        );
    });

    return deferred.promise;
}

How to write curl 'PUT' request in node with 'request' module


Tag : node.js , By : user135518
Date : March 29 2020, 07:55 AM
I wish this helpful for you After trying several approaches, while I couldn't reproduce your specific problem, the trouble I had was with the binary attachment loading properly. Because createReadStream() runs asynchronously, it doesn't really seem to work the way the request docs say it should when added to the multipart or formData keys. Not sure why this is?
I got it working first using http://requestb.in - comparing the curl request to the same request constructed with Node. Here is the final, working version:
var request = require('request')
fs = require('fs')

var options = {
    uri: 'https://developer.api.autodesk.com/oss/v2/buckets/<yourBucket>/objects/<yourFile.ext>',
    headers: {
        'Content-Type': 'application/octet-stream',
        'Authorization': 'Bearer <token>'
    }
}

fs.createReadStream(__dirname + '/<fileName.ext>').pipe(request.put(options, function(err, response, body) {
    console.log(body)
    /*
        {
          "bucketKey" : "< yourBucket>",
          "objectId" : "urn:adsk.objects:os.object:brandontestbucket2/skyscpr1.3ds",
          "objectKey" : "<fileName.ext>",
          "sha1" : "...redacted...",
          "size" : 43791,
          "contentType" : "application/octet-stream",
          "location" : "https://developer.api.autodesk.com/oss/v2/buckets/< yourBucket>/objects/<fileName.ext>"
        }
    */
}))

Is there a way to validate fields in a Request Object that am using as a wrapper, such that one of them is optional


Tag : spring , By : Sanoran
Date : March 29 2020, 07:55 AM
wish of those help This can be achieved using javax.validation.Constraint. Annotate your controller using @Validate annotation, and you can create your constraints as below:
Controller
import com.example.model.Employee;
import com.example.model.InputForm;
import com.example.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@RestController
@Validated
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value="/update", method= RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResponseEntity<List<Employee>> update(
            HttpServletRequest request,
            @CheckAtLeastOnePresentConstraint @RequestBody @Valid InputForm form,
            HttpServletResponse response
    )  {
        return new ResponseEntity<List<Employee>>(myService.getEmployees(form), HttpStatus.OK);
    }
}
import java.lang.annotation.*;

import javax.validation.Constraint;
import javax.validation.Payload;


@Constraint(validatedBy = CheckOneValuePresent.class)
@Target( { ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckAtLeastOnePresentConstraint {
    String message() default "At least one of the values removeEmpList or addEmpList must be present";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraintvalidation.SupportedValidationTarget;
import javax.validation.constraintvalidation.ValidationTarget;

@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class CheckOneValuePresent implements ConstraintValidator<CheckAtLeastOnePresentConstraint, InputForm> {

    @Override
    public boolean isValid(InputForm inputForm,
        ConstraintValidatorContext cxt) {
        return inputForm.getAddEmpList() != null || inputForm.getRemoveEmpList() != null;
    }
}
Related Posts Related QUESTIONS :
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • Are frameworks misleadingly named for marketing purposes?
  • React <Redirect> after transition not working
  • How to send multiple parameters in a function using EJS
  • React conditional style on custom click
  • Push a block of information to an array X times based on an external variable
  • How do I populate dropdown with names, and values (numeric ids)?
  • How to apply styling to elements created with .insertAdjacentHtml method
  • Positioning key:value of an object
  • Referencing DOM Elements with React Hooks
  • TypeError: Method "getRange" of null when using multiple scripts (Libraries) in Google scripts
  • Why can't I check if an environment variable is undefined?
  • Is there a way to find what parts are the same between two strings?
  • Every change done with magicscroll and greensock get reset when I hit the bottom of the page
  • Fix a 'Cannot read property handleClick of undefined error' (and issues related to deleting an item from the DOM)
  • Answer to message if sent within a period of time
  • Enabling a button based on selected values
  • Get All possible matches between forward slashes
  • get the CSS maxWidth value of the parent javascript
  • Async function returning existing array as undefined
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com