Вот мой файл резольвера:
import { gql } from 'apollo-server-express'
import * as db from '../database'
export const typeDefs = gql`
extend type Query {
getFoos(): Foo
}
type Foo {
id: ID!
missingBar: [String]
}
input addBarInput {
fooId: ID!
barId: ID!
}
extend type Mutation {
addBar(input: addBarInput): Foo
startFoo(fooId: ID!): Foo
}
`
export const resolvers = {
Query: {
getFoos: async () => db.foo.findAll({include: [db.bar]}),
},
Foo: {
missingBar: async (obj, args, context, info) => {
// here starts the relevant part of code
const someBarIds = await db.some_table.findAll({
where: {bar_id: obj.bar_id},
}).map(el => el.bar_id)
const otherBarIds = await db.other_table.findAll({
where: {id: obj.bars.map(b => b.id)},
}).map(el => el.id)
const missingBarIds = someBarIds.filter(x => !otherBarIds.includes(x));
// here ends the relevant part of code
return await db.instruments.findAll({where: {id: missingInstrumentsIds}}).map(instrument => instrument.name)
},
},
Mutation: {
addBar: async (prev, { input }) => {
const foo = await db.foo.findByPk(input.fooId)
const bar = await db.users.findByPk(input.userId)
await bar.setBar(foo)
return foo
},
startFoo: async (prev, { input }) => {
const foo = await db.foo.findByPk(input.fooId)
// here I would like to have the code from missingBar without copypasting it
// then I need to do more logic (irrelevant for this question) using that missingBarIds array
return foo
},
}
}
Как примечание, я не думаю, что точная логика Sequelize c в резольвере missingBar
важна для сути вопроса, поэтому я упростили это Суть в том, что я хочу выполнить обновление БД, только если все необходимые элементы были добавлены в foo
, и эта проверка выполняется с точно таким же логом c, что и в missingBar
resolver.
Есть ли способ разделить части логики c между различными мутациями и распознавателями? В идеале, объявить функцию где-нибудь и использовать ее в обоих местах?
В этом случае единственным параметром этой гипотетической функции c будет экземпляр объекта foo
(который является моделью Sequelize, но опять-таки я не думаю, что это действительно актуально в данном случае), и возвращаемое значение будет таким missingBarIds
массивом.