Created
December 20, 2018 13:39
-
-
Save alexFaunt/a48000b09b68188c225ec99aeebb78e9 to your computer and use it in GitHub Desktop.
No mixins pattern
This file contains hidden or 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 createModelHelpers = (model) => { | |
const query = (trx) => model.query(trx).withSchema('workout'); | |
const getById = ({ trx, id }) => query(trx).findById(id); | |
const insert = async ({ trx, input }) => query(trx).insert(input).returning('*'); | |
return { | |
query, | |
getById, | |
insert, | |
}; | |
}; | |
const { | |
query, | |
getById, | |
insert, | |
} = createModelHelpers(TrainerModel); | |
export const createLoader = ({ knex }) => { | |
TrainerModel.knex(knex); | |
return { | |
// Exposing getById | |
getById, | |
// Custom insert implementation | |
insert: async ({ input }) => { | |
// Validate input | |
const inserted = await insert({ input }); | |
return inserted; | |
}, | |
custom: async ({ id }) => { | |
// Start a new transaction | |
const result = await transaction(TrainerModel, async (TransactionModel, trx) => { | |
// Use the bound version of the transaction model directly | |
const trainer = await TransactionModel.findById(id); | |
// Use the bound version or the transaction in the query helper | |
const other = await query(TransactionModel).findById(id); | |
const third = await query(trx).findById(id); | |
// Update any random table | |
const inserted = await trx('random_table').insert({ stuff: trainer.updatedAt }); | |
return { inserted, other, third }; | |
}); | |
// custom return type for some reason | |
return { | |
...result, | |
custom: 'stuff', | |
}; | |
}, | |
}; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment