Skip to content

Instantly share code, notes, and snippets.

@jgeewax
Last active October 26, 2015 18:58
Show Gist options
  • Save jgeewax/3b351d3522fdf061bdea to your computer and use it in GitHub Desktop.
Save jgeewax/3b351d3522fdf061bdea to your computer and use it in GitHub Desktop.
var express = require('express');
var app = express();
var gcloud = require('gcloud')({ /* extra config here */ });
var dataset = gcloud.datastore.dataset({ /* projectId: my-project */ });
// Set the trace ID on a per-request basis via middleware
// (See http://expressjs.com/guide/writing-middleware.html)
app.use(function(req, res, next) {
// Need to double check that this works from a thread safety perspective.
gcloud.setTraceContext(req.headers['X-Cloud-Trace-Context']);
});
// Get companies from the datastore.
app.get('/company/:id', function(req, res, next) {
var key = dataset.Key(['Company', req.params.id]);
// This request will have the trace ID that was set by the middleware.
// So whatever was in the request header will be automatically forwarded along.
dataset.get(key).on('data', function(entity) {
res.send(entity);
});
});
@stephenplusplus
Copy link

In that example, bucket.getMetadata() would not know anything about the decorated request options. You would have to access the bucket from threadLocalgcloud.bucket() to have that stuff on there.

In a practical use, if I need to decorate all requests, I would do this:

var gcloud = require('gcloud')({
  decorateRequest: function(reqOpts) {
    reqOpts.headers['A'] = 1;
    reqOpts.headers['B'] = 1;
    return reqOpts;
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment