Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. const co = require('co');
  2. const stream = require('stream');
  3.  
  4.  
  5. function S3InMemoryClient() {
  6. var memFs = {};
  7.  
  8. const client = {
  9. upload: (opts, cb) => co(function*() {
  10. const data = opts.Body instanceof stream.Readable ?
  11. yield readStream(opts.Body) : opts.Body;
  12. const key = [opts.Bucket, opts.Key].join('/');
  13.  
  14. memFs[key] = data;
  15. }).then(() => cb(), err => cb(err)),
  16.  
  17. getObject: (opts) => ({
  18. createReadStream: () => {
  19. const key = [opts.Bucket, opts.Key].join('/');
  20. const buf = memFs[key];
  21.  
  22. return buf ? ContentStream(buf) : ErrorStream(new Error(`${key} was not mocked`));
  23. }
  24. }),
  25.  
  26. listObjects: (s3Opts, cb) => {
  27. const fsPrefix = [s3Opts.Bucket, s3Opts.Prefix].join('/');
  28.  
  29. const matchingKeys = Object.keys(memFs)
  30. .filter(fsKey => fsKey.startsWith(fsPrefix))
  31. .map(fsKey => fsKey.slice(s3Opts.Bucket.length + 1));
  32.  
  33. cb(null, {
  34. Contents: matchingKeys.map(Key => ({ Key }))
  35. });
  36. }
  37. };
  38.  
  39. return client;
  40. }
  41.  
  42.  
  43. function ContentStream(buffer) {
  44. const mockStream = new stream.PassThrough();
  45. setTimeout(() => mockStream.end(buffer));
  46. return mockStream;
  47. }
  48.  
  49. function ErrorStream(err) {
  50. const mockStream = new stream.PassThrough();
  51. setTimeout(() => mockStream.emit('error', err), 10);
  52. return mockStream;
  53. }
  54.  
  55. /**
  56. * @param {stream.Readable} stream
  57. * @returns {Promise<Buffer>}
  58. */
  59. function readStream(stream) {
  60. return co(function*() {
  61. var buf = new Buffer(0);
  62. yield cb => stream
  63. .on('data', data => buf = Buffer.concat([buf, data]))
  64. .on('error', cb)
  65. .on('end', cb);
  66.  
  67. return buf;
  68. })
  69. }
  70.  
  71.  
  72. module.exports = S3InMemoryClient;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement