Last active
October 7, 2017 18:35
-
-
Save deptno/fd5dd01f4b4e574b1b3df026957c46cd to your computer and use it in GitHub Desktop.
redux middleware - db sync
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
import {Middleware} from 'redux' | |
import {CollectionInsertManyOptions, CollectionInsertOneOptions, MongoClient} from 'mongodb' | |
export interface Argument { | |
mongoDbUrl: string | |
dbCollectionPrefix: string | |
insertOneOptions?: CollectionInsertOneOptions | |
insertManyOptions?: CollectionInsertManyOptions | |
} | |
export function createMongoDbSyncMiddleware(argument: Argument): Middleware { | |
const {mongoDbUrl, dbCollectionPrefix, insertOneOptions, insertManyOptions} = argument | |
if (!mongoDbUrl || !dbCollectionPrefix) { | |
throw new Error('createMongoDbSyncMiddleware({mongoDbUrl, dbCollectionPrefix})') | |
} | |
return ({dispatch, getState}) => | |
next => | |
action => { | |
const {type, payload} = action | |
const [requestType, name] = type.split(' ') | |
if (requestType === 'success') { | |
process.nextTick(async () => { | |
if (!payload) { | |
return | |
} | |
try { | |
const db = await MongoClient.connect(mongoDbUrl) | |
try { | |
const collection = db.collection(`${dbCollectionPrefix}.${name}`) | |
if (Array.isArray(payload)) { | |
await collection.insertMany(payload, insertManyOptions) | |
} else { | |
await collection.insertOne(payload, insertOneOptions) | |
} | |
} catch (ex) { | |
console.error(JSON.stringify(ex, null, 2)) | |
} finally { | |
db.close() | |
} | |
} catch (ex) { | |
console.error(JSON.stringify(ex, null, 2)) | |
} | |
}) | |
} | |
return next(action) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment