Last active
November 17, 2015 06:22
-
-
Save mtth/5cd7e3f62e258a545291 to your computer and use it in GitHub Desktop.
Instrument Avro types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* jshint node: true */ | |
'use strict'; | |
var avsc = require('avsc'); | |
/** | |
* Function returning an instrumented type. | |
* | |
* @param schema {Object} Schema to parse. | |
* | |
* When passed a buffer to decode, the instrumented type will return a | |
* wrapped decoded value, with start and end markers for each value. | |
* | |
* Sample usage: | |
* | |
* var instrumentedType = instrument(schema); | |
* var obj = instrumentedType.fromBuffer(buf); | |
* | |
*/ | |
function instrument(schema) { | |
if (schema instanceof avsc.types.Type) { | |
schema = schema.getSchema(); | |
} | |
var refs = []; // Array of previously seen schemas, to avoid cycles. | |
return avsc.parse(schema, {typeHook: hook}); | |
function hook(schema, opts) { | |
if (~refs.indexOf(schema)) { | |
return; | |
} | |
refs.push(schema); | |
if (schema.type === 'record') { | |
// Defaults (if any) won't correspond to the wrapped schema, we remove | |
// them (they wouldn't be used anyway). | |
schema.fields.forEach(function (f) { f['default'] = undefined; }); | |
} | |
var name = schema.name; | |
if (name) { | |
// Rewire the name (attaching it to the wrapper and replacing the | |
// original schema's) for name references to work correctly. | |
schema.name = 'r' + Math.random().toString(36).substr(2, 6); | |
} | |
var wrappedSchema = { | |
name: name || 'r' + Math.random().toString(36).substr(2, 6), | |
namespace: schema.namespace, | |
type: 'record', | |
fields: [{name: 'value', type: schema}] | |
}; | |
refs.push(wrappedSchema); | |
// Create type and override read method to place start and end markers. | |
var type = avsc.parse(wrappedSchema, opts); | |
var read = type._read; | |
type._read = function (tap) { | |
var pos = tap.pos; | |
var obj = read.call(type, tap); | |
obj.start = pos; | |
obj.end = tap.pos; | |
return obj; | |
}; | |
return type; | |
} | |
} | |
/** | |
* Convenience method to instrument a single object. | |
* | |
* @param type {Type} The type to be instrumented. | |
* @param obj {Object} A valid instance of `type`. | |
* | |
* Returns an representation of `obj` with start and end markers. | |
* | |
*/ | |
function instrumentObject(type, obj) { | |
return instrument(type).fromBuffer(type.toBuffer(obj)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example: