Skip to content

Instantly share code, notes, and snippets.

@alexFaunt
Created December 20, 2018 13:39
Show Gist options
  • Save alexFaunt/a48000b09b68188c225ec99aeebb78e9 to your computer and use it in GitHub Desktop.
Save alexFaunt/a48000b09b68188c225ec99aeebb78e9 to your computer and use it in GitHub Desktop.
No mixins pattern
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