Skip to content

Instantly share code, notes, and snippets.

@nfarina
Last active November 23, 2023 15:50
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save nfarina/90ba99a5187113900c86289e67586aaa to your computer and use it in GitHub Desktop.
Save nfarina/90ba99a5187113900c86289e67586aaa to your computer and use it in GitHub Desktop.
Mock Google Cloud Storage for JS
//
// Quick & Dirty Google Cloud Storage emulator for tests. Requires
// `stream-buffers` from npm. Use it like this:
//
// `new MockStorage().bucket('my-bucket').file('my_file').createWriteStream()`
//
class MockStorage {
buckets: {[name: string]: MockBucket};
constructor() {
this.buckets = {};
}
bucket(name: string) {
return this.buckets[name] ||
(this.buckets[name] = new MockBucket(name));
}
}
class MockBucket {
name: string;
files: {[path: string]: MockFile};
constructor(name: string) {
this.name = name;
this.files = {};
}
file(path: string) {
return this.files[path] ||
(this.files[path] = new MockFile(path));
}
}
class MockFile {
path: string;
contents: Buffer;
metadata: Object;
constructor(path: string) {
this.path = path;
this.contents = new Buffer(0);
this.metadata = {};
}
get() {
return [this, this.metadata];
}
setMetadata(metadata: Object) {
const customMetadata = {...this.metadata.metadata, ...metadata.metadata};
this.metadata = {...this.metadata, ...metadata, metadata: customMetadata};
}
createReadStream() {
const streamBuffers = require('stream-buffers');
const readable = new streamBuffers.ReadableStreamBuffer();
readable.put(this.contents);
readable.stop();
return readable;
}
createWriteStream({metadata}: Object) {
this.setMetadata(metadata);
const streamBuffers = require('stream-buffers');
const writable = new streamBuffers.WritableStreamBuffer();
writable.on('finish', () => {
this.contents = writable.getContents();
});
return writable;
}
delete() {
return Promise.resolve();
}
}
@shotah
Copy link

shotah commented Apr 8, 2023

@aldipermanaetikaputra I have a Datastore one if you'd like that as well. I couldn't find this packages repo so I couldn't file issues or contribute back. https://www.npmjs.com/package/datastore-mock?activeTab=readme So I forked it to a script. Would be nice if it could get maintained and updated.

@nfarina
Copy link
Author

nfarina commented Apr 8, 2023

I have a rather-insane Firestore one as well :) actually works...but it only implements the "compat" API

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