-
Notifications
You must be signed in to change notification settings - Fork 10
Creating a model
A model it's an async function who receive the connectors and environment variables and return a new object, your real model. That object it's intended to receive the arguments and HTTP request object from your resolvers and have your business logic.
A model your check if you are logged or if you have the required permissions and must have methods to create, read, update or delete data using connectors.
You can either have completely custom models or use the models of a ORM or ODM like Sequelize or Mongoose.
exports.Pokemon = async function Pokemon({ pokeapi }) {
return {
getSingle(number) {
return pokeapi.read({ resource: 'pokemon', id: number });
},
};
};
That example model use the pokeapi
connector to get a single Pokemon data, it return an object with the method to do that. That's a extremelly simple model but you can extend it as you want.
Thanks to the injection of connectors inside your models you can test how they work simple mocking your connectors API. In the above example we can create a mock for the pokeapi connector using a plain object with a read
method.
Then we can create a simple test that create a new instance of the pokemon model and run the getSingle
method.
const { Pokemon } = require('./models.js');
describe('Pokemon model', () => {
it('should get a single pokemon data', async () => {
const pokemon {
id: 25,
name: 'Pikachu',
};
const pokeapi = {
read({ resource, id }) {
expect(resource).toBe('pokemon')
expect(id).toBe(25)
return pokemon;
},
};
const model = await Pokemon({ pokeapi })
expect(model.getSingle({ resource: 'pokemon', id: 25 })).toBe(pokemon);
});
});