Skip to content

Instantly share code, notes, and snippets.

@SirSerje
Created April 10, 2020 13:11
Show Gist options
  • Save SirSerje/efe1d20b4b379350b2bba1384e641859 to your computer and use it in GitHub Desktop.
Save SirSerje/efe1d20b4b379350b2bba1384e641859 to your computer and use it in GitHub Desktop.
write and read string to mongo
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import { Readable } from 'stream'
let bucket;
const envConfig = dotenv.config();
if (envConfig.error) {
console.log('.env file does not loaded');
throw envConfig.error;
}
mongoose.connect(process.env.MONGO_PATH, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}).then((result) => {
console.log(`MongoDB connection granted`);
bucket = new mongoose.mongo.GridFSBucket(db.db);
run()
}).catch(error => console.log(`There is troubles with connecting to MongoDB ${error}`));
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('success connect');
});
const createMessage = () => ({
phone_number: '+380955555555',
meta: {
phone_number: '+380955555555',
custom: 'custom',
first_name: 'first',
last_name: 'last',
},
rate: 1.1,
mccMnc: 123,
text: 'text',
});
const generateLR = (messageQuantity) => {
return JSON.stringify({
broadcast_id: '1',
messages: Array(messageQuantity).fill(createMessage()),
senders: ['sender1', 'sender2'],
links: ['link1', 'link2'],
unsubscription_list_ids: [1, 2, 3],
});
};
const run = async () => {
const writeToMongo = async (params,data) => {
const { filename } = params;
const uploadStream = bucket.openUploadStream(filename);
return new Promise((resolve, reject) => {
Readable.from(data, {encoding: 'utf8'})
.pipe(uploadStream)
.on('error', () => {
console.log('error');
reject(false)
})
.on('finish', () => {
console.log('done!');
resolve(true)
});
});
};
const readFromMongo = async (params) => {
const { filename } = params;
return new Promise((resolve, reject) => {
let data = '';
const downloadStream = bucket.openDownloadStreamByName(filename);
downloadStream.on('data', (chunk) => data += chunk)
.on('end', () => resolve(data))
.on('error', () => reject('SOME ERROR HAPPEN'))
})
};
let a = await writeToMongo({ filename: 'filename2.txt' }, generateLR(1));
console.log('isSuccess?: ', a);
let b = await readFromMongo({ filename: 'filename2.txt' });
console.log('readResult', b);
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment