keys.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. var test = require('tape');
  2. var fs = require ('fs');
  3. var join = require('path').join;
  4. var couch_sample_file = join(__dirname, 'fixtures','couch_sample.json');
  5. var JSONStream = require('../');
  6. var fixture = {
  7. obj: {
  8. one: 1,
  9. two: 2,
  10. three: 3
  11. }
  12. };
  13. function assertFixtureKeys(stream, t) {
  14. var keys = [];
  15. var values = [];
  16. stream.on('data', function(data) {
  17. keys.push(data.key);
  18. values.push(data.value);
  19. });
  20. stream.on('end', function() {
  21. t.deepEqual(keys, ['one', 'two', 'three']);
  22. t.deepEqual(values, [1,2,3]);
  23. t.end();
  24. });
  25. stream.write(JSON.stringify(fixture));
  26. stream.end();
  27. }
  28. test('keys via string', function(t) {
  29. var stream = JSONStream.parse('obj.$*');
  30. assertFixtureKeys(stream, t);
  31. });
  32. test('keys via array', function(t) {
  33. var stream = JSONStream.parse(['obj',{emitKey: true}]);
  34. assertFixtureKeys(stream, t);
  35. });
  36. test('path via array', function(t) {
  37. var stream = JSONStream.parse(['obj',{emitPath: true}]);
  38. var paths = [];
  39. var values = [];
  40. stream.on('data', function(data) {
  41. console.log(JSON.stringify(data));
  42. paths.push(data.path);
  43. values.push(data.value);
  44. });
  45. stream.on('end', function() {
  46. t.deepEqual(paths, [['obj', 'one'], ['obj', 'two'], ['obj', 'three']]);
  47. t.deepEqual(values, [1,2,3]);
  48. t.end();
  49. });
  50. stream.write(JSON.stringify(fixture));
  51. stream.end();
  52. });
  53. test('advanced keys', function(t) {
  54. var advanced = fs.readFileSync(couch_sample_file);
  55. var stream = JSONStream.parse(['rows', true, 'doc', {emitKey: true}]);
  56. var keys = [];
  57. var values = [];
  58. stream.on('data', function(data) {
  59. keys.push(data.key);
  60. values.push(data.value);
  61. });
  62. stream.on('end', function() {
  63. t.deepEqual(keys, [
  64. '_id', '_rev', 'hello',
  65. '_id', '_rev', 'hello'
  66. ]);
  67. t.deepEqual(values, [
  68. "change1_0.6995461115147918", "1-e240bae28c7bb3667f02760f6398d508", 1,
  69. "change2_0.6995461115147918", "1-13677d36b98c0c075145bb8975105153", 2
  70. ]);
  71. t.end();
  72. });
  73. stream.write(advanced);
  74. stream.end();
  75. });
  76. test('parent keys', function(t) {
  77. var stream = JSONStream.parse('$*');
  78. var d = null;
  79. stream.on('data', function(data) {
  80. if(d) t.fail('should only be called once');
  81. d = data;
  82. });
  83. stream.on('end', function() {
  84. t.deepEqual(d,{
  85. key: 'obj',
  86. value: fixture.obj
  87. });
  88. t.end();
  89. });
  90. stream.write(JSON.stringify(fixture));
  91. stream.end();
  92. })