Last active
August 20, 2019 05:33
-
-
Save copperwall/2dade3cd282207f4aad9a7eef3f16bbc to your computer and use it in GitHub Desktop.
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
const util = require('util'); | |
const S3 = require('aws-sdk/clients/s3'); | |
const client = new S3(); | |
const createBucket = util.promisify(client.createBucket); | |
const upload = util.promisify(client.upload); | |
const getObject = util.promisify(client.getObject); | |
client.createBucket = createBucket; | |
client.upload = upload; | |
client.getObject = getObject; | |
client.createBucket({ | |
Bucket: 'dataproxy' | |
}); | |
function createS3Object(id, type, obj?: object) { | |
if (obj) { | |
obj = { | |
...obj, | |
id | |
}; | |
} | |
let remoteValue = client.getObject({ | |
Bucket: 'copperwall-woopwoop', | |
Key: `${type}/${id}` | |
}).then(res => JSON.parse(res.Body.toString()) | |
).catch(err => { | |
// This happens if the key doesn't exist, which is fine. | |
let uploadResponse = Promise.resolve(); | |
if (obj) { | |
uploadResponse = client.upload({ | |
Bucket: 'copperwall-woopwoop', | |
Key: `${type}/${id}`, | |
Body: Buffer.from(JSON.stringify(obj)) | |
}); | |
} | |
return uploadResponse; | |
}).then(() => { | |
return client.getObject({ | |
Bucket: 'copperwall-woopwoop', | |
Key: `${type}/${id}` | |
}); | |
}).then(res => JSON.parse(res.Body.toString())); | |
return new Proxy<any>({}, { | |
// Is there a use case for the local version? | |
get(target, p) { | |
return remoteValue.then(obj => { | |
return obj[p]; | |
}); | |
}, | |
set(target, p, value) { | |
target[p] = value; | |
remoteValue = remoteValue.then(obj => { | |
const merged = { | |
...obj, | |
...{ [p]: value } | |
}; | |
return client.upload({ | |
Bucket: 'copperwall-woopwoop', | |
Key: `${type}/${id}`, | |
Body: Buffer.from(JSON.stringify(merged)) | |
}); | |
}).then(() => { | |
return client.getObject({ | |
Bucket: 'copperwall-woopwoop', | |
Key: `${type}/${id}` | |
}); | |
}).then(res => JSON.parse(res.Body.toString())); | |
return true; | |
} | |
}); | |
} | |
async function coolStuff() { | |
await client.createBucket({ | |
Bucket: 'dataproxy' | |
}); | |
const firstObj = createS3Object(1, "testing", { name: "copperwall", stuff: "also" }); | |
console.log('wat'); | |
firstObj.firstField = "hello"; | |
let firstField = await firstObj.firstField; | |
console.log(firstField); | |
firstObj.firstField = "woop"; | |
firstField = await firstObj.firstField; | |
console.log(firstField) | |
} | |
async function coolStuff2() { | |
const firstObj = createS3Object(1, "testing"); | |
console.log(await firstObj.name); | |
} | |
coolStuff().then(() => { | |
coolStuff2(); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment