-
Notifications
You must be signed in to change notification settings - Fork 447
3. Back end
Food Advisor's back-end is built with Strapi.
You can find out how to run Strapi in the Readme
- Strapi version: 3.0.0-alpha.24.1
- Database: SQLite
We are using Strapi's capacity to bootstrap APIs quickly.
We built the following Content Types:
- Category
- Like
- Restaurant
- Review
Food Advisor's front-end is built using React and GraphQL so we decided to use the graphql
plugin.
📚 Plugin documentation here.
When using the graphql
plugin you need to ensure you update your API schema if you start adding custom behaviors within your APIs.
Here, for example, we added two fields (note
and noteDetails
) and a new Resolver to count the Restaurants.
Path - ./api/restaurant/config/schema.graphql.js
module.exports = {
definition: /* GraphQL */ `
extend type Restaurant {
note: Float
noteDetails: [RestaurantNote!]!
}
type RestaurantsConnection {
aggregate: RestaurantsAggregate
}
type RestaurantsAggregate {
count: Int
}
type RestaurantNote {
note: Int
count: Int
}
`,
query: /* GraphQL */ `
restaurantsConnection(where: JSON): RestaurantsConnection
`,
resolver: {
Query: {
restaurantsConnection(_, args) {
return args;
}
},
RestaurantsConnection: {
aggregate(args) {
return args;
}
},
RestaurantsAggregate: {
count(args) {
return strapi.controllers.restaurant.count({
query: args.where || {}
});
}
}
}
};
📚Custom schema documentation here.
To add the note
and noteDetails
attributes that don't exist (at this point) in the data model of a Restaurant, we customize the controller to add it in the data response.
In the Review API we create a new service function called average
. This function receives the Restaurant ID and then fetches its average Review note
.
Path - ./api/review/services/Review.js
return Review.query(function(qb) {
qb.avg('note');
qb.where('restaurant', '=', restaurant);
}).fetch();
Here we use the knex
query function available in the Global variable of the model.
Then to apply it in the response data, we call the service function in the Restaurant API controller findOne
function.
Path - ./api/restaurant/services/Restaurant.js
let note = await strapi.api.review.services.review.average(restaurant.id);
Following this line we have additional modifications that extract the correct data.
For this application we are using a SQLite database. This allows us to quickly create a seed script by dumping the database into a data.zip
and unzipping it upon install.