Backend customization
Backend customization
Routing
./api/**/config/routes.json files define all available endpoints for the clients.
By default, Strapi generates endpoints for all your Content Types. More information is in the Content API documentation.
How to create a route?
You have to edit the routes.json file in one of your APIs folders (./api/**/config/routes.json) and manually add a new route object into the routes array.
Path — ./api/**/config/routes.json.
{
"routes": [
{
"method": "GET",
"path": "/restaurants",
"handler": "Restaurant.find",
"config": {
"policies": []
}
},
{
"method": "PUT",
"path": "/restaurants/bulkUpdate",
"handler": "Restaurant.bulkUpdate",
"config": {
"policies": []
}
},
{
"method": "POST",
"path": "/restaurants/:id/reservation",
"handler": "Restaurant.reservation",
"config": {
"policies": ["isAuthenticated", "hasCreditCard"]
}
}
]
}
method(string): Method or array of methods to hit the route (e.g.GET,POST,PUT,HEAD,DELETE,PATCH).path(string): URL starting with/(e.g./restaurants).handler(string): Action to execute when the route is hit following this syntax<Controller>.<action>.configpolicies(array): Array of policy names or paths (see more)
TIP
You can exclude the entire config object if you do not want the route to be checked by the Users & Permissions plugin.
Dynamic parameters
The router used by Strapi allows you to create dynamic routes where you can use parameters and simple regular expressions. These parameters will be exposed in the ctx.params object. For more details, please refer to the PathToRegex
(opens new window) documentation.
{
"routes": [
{
"method": "GET",
"path": "/restaurants/:category/:id",
"handler": "Restaurant.findOneByCategory",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/restaurants/:region(\\d{2}|\\d{3})/:id", // Only match when the first parameter contains 2 or 3 digits.
"handler": "Restaurant.findOneByRegion",
"config": {
"policies": []
}
}
]
}
Example
Route definition with URL params
{
"routes": [
{
"method": "GET",
"path": "/restaurants/:id",
"handler": "Restaurant.findOne",
"config": {
"policies": []
}
}
]
}
Get the URL param in the controller
module.exports = {
findOne: async ctx => {
// const id = ctx.params.id;
const { id } = ctx.params;
return id;
},
};
Policies
Policies are functions which have the ability to execute specific logic on each request before it reaches the controller‘s action. They are mostly used for securing business logic easily. Each route of the project can be associated to an array of policies. For example, you can create a policy named isAdmin, which obviously checks that the request is sent by an admin user, and use it for critical routes.
The policies are defined in each ./api/**/config/policies/ folders and plugins. They are respectively exposed through strapi.api.**.config.policies and strapi.plugins.**.config.policies. The global policies are defined at ./config/policies/ and accessible via strapi.config.policies.
How to create a policy?
There are several ways to create a policy.
- Using the CLI
strapi generate:policy isAuthenticated. Read the CLI documentation for more information. - Manually create a JavaScript file named
isAuthenticated.jsin./config/policies/.
Path — ./config/policies/isAuthenticated.js.
module.exports = async (ctx, next) => {
if (ctx.state.user) {
// Go to next policy or will reach the controller's action.
return await next();
}
ctx.unauthorized(`You're not logged in!`);
};
In this example, we are verifying that a session is open. If it is the case, we call the next() method that will execute the next policy or controller‘s action. Otherwise, a 401 error is returned.
Usage
To apply policies to a route, you need to associate an array of policies to it. There are two kinds of policies: global and scoped.
WARNING
To apply policies with GraphQL please see the following guide.
Global policies
The global policies can be associated to any route in your project.
Path — ./api/restaurant/routes.json.
{
"routes": [
{
"method": "GET",
"path": "/restaurants",
"handler": "Restaurant.find",
"config": {
"policies": ["global::isAuthenticated"]
}
}
]
}
Before executing the find action in the Restaurant.js controller, the global policy isAuthenticated located in ./config/policies/isAuthenticated.js will be called.
TIP
You can put as much policy as you want in this array. However be careful about the performance impact.
Plugins policies
Plugins can add and expose policies into your app. For example, the plugin Users & Permissions comes with useful policies to ensure that the user is well authenticated or has the rights to perform an action.
Path — ./api/restaurant/config/routes.json.
{
"routes": [
{
"method": "GET",
"path": "/restaurants",
"handler": "Restaurant.find",
"config": {
"policies": ["plugins::users-permissions.isAuthenticated"]
}
}
]
}
The policy isAuthenticated located in the users-permissions plugin will be executed before the find action in the Restaurant.js controller.
API policies
The API policies can be associated to the routes defined in the API where they have been declared.
Path — ./api/restaurant/config/policies/isAdmin.js.
module.exports = async (ctx, next) => {
if (ctx.state.user.role.name === 'Administrator') {
// Go to next policy or will reach the controller's action.
return await next();
}
ctx.unauthorized(`You're not allowed to perform this action!`);
};
Path — ./api/restaurant/config/routes.json.
{
"routes": [
{
"method": "GET",
"path": "/restaurants",
"handler": "Restaurant.find",
"config": {
"policies": ["isAdmin"]
}
}
]
}
The policy isAdmin located in ./api/restaurant/config/policies/isAdmin.js will be executed before the find action in the Restaurant.js controller.
Using a policy outside its api
To use a policy in another api you can reference it with the following syntax: {apiName}.{policyName}.
Path — ./api/category/config/routes.json.
{
"routes": [
{
"method": "GET",
"path": "/categories",
"handler": "Category.find",
"config": {
"policies": ["restaurant.isAdmin"]
}
}
]
}
Advanced usage
As it‘s explained above, the policies are executed before the controller’s action. It looks like an action that you can make before the controller’s action. You can also execute a logic after.
Path — ./config/policies/custom404.js.
module.exports = async (ctx, next) => {
// Indicate to the server to go to
// the next policy or to the controller's action.
await next();
// The code below will be executed after the controller's action.
if (ctx.status === 404) {
ctx.body = 'We cannot find the resource.';
}
};
Controllers
Controllers are JavaScript files which contain a set of methods called actions reached by the client according to the requested route. It means that every time a client requests the route, the action performs the business logic coded and sends back the response. They represent the C in the MVC pattern. In most cases, the controllers will contain the bulk of a project‘s business logic.
module.exports = {
// GET /hello
async index(ctx) {
return 'Hello World!';
},
};
In this example, any time a web browser is pointed to the /hello URL on your app, the page will display the text: Hello World!.
The controllers are defined in each ./api/**/controllers/ folder. Every JavaScript file put in these folders will be loaded as a controller. They are also available through the strapi.controllers and strapi.api.**.controllers global variables.
Core controllers
When you create a new Content Type you will see a new empty controller has been created. This is because Strapi builds a generic controller for your models by default and allows you to override and extend it in the generated files.
Extending a Model Controller
Here are the core methods (and their current implementation). You can simply copy and paste this code in your own controller file to customize the methods.
WARNING
In the following example we will assume your controller, service and model are named restaurant
Utils
First require the utility functions
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
parseMultipartData: This function parses Strapi‘s formData format.sanitizeEntity: This function removes all private fields from the model and its relations.
Collection Type
find
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Retrieve records.
*
* @return {Array}
*/
async find(ctx) {
let entities;
if (ctx.query._q) {
entities = await strapi.services.restaurant.search(ctx.query);
} else {
entities = await strapi.services.restaurant.find(ctx.query);
}
return entities.map(entity => sanitizeEntity(entity, { model: strapi.models.restaurant }));
},
};
findOne
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Retrieve a record.
*
* @return {Object}
*/
async findOne(ctx) {
const { id } = ctx.params;
const entity = await strapi.services.restaurant.findOne({ id });
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
count
module.exports = {
/**
* Count records.
*
* @return {Number}
*/
count(ctx) {
if (ctx.query._q) {
return strapi.services.restaurant.countSearch(ctx.query);
}
return strapi.services.restaurant.count(ctx.query);
},
};
create
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Create a record.
*
* @return {Object}
*/
async create(ctx) {
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.restaurant.create(data, { files });
} else {
entity = await strapi.services.restaurant.create(ctx.request.body);
}
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
update
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Update a record.
*
* @return {Object}
*/
async update(ctx) {
const { id } = ctx.params;
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.restaurant.update({ id }, data, {
files,
});
} else {
entity = await strapi.services.restaurant.update({ id }, ctx.request.body);
}
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
delete
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Delete a record.
*
* @return {Object}
*/
async delete(ctx) {
const { id } = ctx.params;
const entity = await strapi.services.restaurant.delete({ id });
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
Single Type
find
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Retrieve the record.
*
* @return {Object}
*/
async find(ctx) {
const entity = await strapi.services.restaurant.find();
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
update
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Update the record.
*
* @return {Object}
*/
async update(ctx) {
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.restaurant.createOrUpdate(data, {
files,
});
} else {
entity = await strapi.services.restaurant.createOrUpdate(ctx.request.body);
}
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
delete
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Delete the record.
*
* @return {Object}
*/
async delete(ctx) {
const entity = await strapi.services.restaurant.delete();
return sanitizeEntity(entity, { model: strapi.models.restaurant });
},
};
Custom controllers
You can also create custom controllers to build your own business logic and API endpoints.
There are two ways to create a controller:
- Using the CLI
strapi generate:controller restaurant. Read the CLI documentation for more information. - Manually create a JavaScript file in
./api/**/controllers.
Adding Endpoints
Each controller‘s action must be an async function. Every action receives a context (ctx) object as first parameter containing the request context and the response context.
Example
In this example, we are defining a specific route in ./api/hello/config/routes.json that takes Hello.index as handler. For more information on routing, please see the Routing documentation
It means that every time a request GET /hello is sent to the server, Strapi will call the index action in the Hello.js controller. Our index action will return Hello World!. You can also return a JSON object.
Path — ./api/hello/config/routes.json.
{
"routes": [
{
"method": "GET",
"path": "/hello",
"handler": "Hello.index",
"config": {
"policies": []
}
}
]
}
Path — ./api/hello/controllers/Hello.js.
module.exports = {
// GET /hello
async index(ctx) {
ctx.send('Hello World!');
},
};
TIP
A route handler can only access the controllers defined in the ./api/**/controllers folders.
Requests & Responses
Requests
The context object (ctx) contains all the requests related information. They are accessible through ctx.request, from controllers and policies.
Strapi passes the body on ctx.request.body and files through ctx.request.files
For more information, please refer to the Koa request documentation
(opens new window).
Responses
The context object (ctx) contains a list of values and functions useful to manage server responses. They are accessible through ctx.response, from controllers and policies.
For more information, please refer to the Koa response documentation
(opens new window).
Services
Services are a set of reusable functions. They are particularly useful to respect the DRY (don‘t repeat yourself) programming concept and to simplify controllers logic.
Core services
When you create a new Content Type or a new model, you will see a new empty service has been created. It is because Strapi builds a generic service for your models by default and allows you to override and extend it in the generated files.
Extending a Model Service
Here are the core methods (and their current implementation). You can simply copy and paste this code to your own service file to customize the methods.
You can read about strapi.query calls here.
TIP
In the following example your controller, service and model are named restaurant.
Utils
If you‘re extending the create or update service, first require the following utility function:
const { isDraft } = require('strapi-utils').contentTypes;
isDraft: This function checks if the entry is a draft.
Collection Type
find
module.exports = {
/**
* Promise to fetch all records
*
* @return {Promise}
*/
find(params, populate) {
return strapi.query('restaurant').find(params, populate);
},
};
params(object): this represent filters for your find request. The object follow the URL query format, refer to this documentation..
{
"name": "Tokyo Sushi"
}
// or
{
"_limit": 20,
"name_contains": "sushi"
}
populate(array): you have to mention data you want populate["author", "author.name", "comment", "comment.content"]
findOne
module.exports = {
/**
* Promise to fetch record
*
* @return {Promise}
*/
findOne(params, populate) {
return strapi.query('restaurant').findOne(params, populate);
},
};
params(object): this represent filters for your find request. The object follow the URL query format, refer to this documentation..
{
"name": "Tokyo Sushi"
}
// or
{
"name_contains": "sushi"
}
populate(array): you have to mention data you want populate["author", "author.name", "comment", "comment.content"]
count
module.exports = {
/**
* Promise to count record
*
* @return {Promise}
*/
count(params) {
return strapi.query('restaurant').count(params);
},
};
params(object): this represent filters for your find request. The object follow the URL query format, refer to this documentation..
{
"name": "Tokyo Sushi"
}
// or
{
"name_contains": "sushi"
}
create
const { isDraft } = require('strapi-utils').contentTypes;
module.exports = {
/**
* Promise to add record
*
* @return {Promise}
*/
async create(data, { files } = {}) {
const isDraft = isDraft(data, strapi.models.restaurant);
const validData = await strapi.entityValidator.validateEntityCreation(
strapi.models.restaurant,
data,
{ isDraft }
);
const entry = await strapi.query('restaurant').create(validData);
if (files) {
// automatically uploads the files based on the entry and the model
await strapi.entityService.uploadFiles(entry, files, {
model: 'restaurant',
// if you are using a plugin's model you will have to add the `source` key (source: 'users-permissions')
});
return this.findOne({ id: entry.id });
}
return entry;
},
};
update
const { isDraft } = require('strapi-utils').contentTypes;
module.exports = {
/**
* Promise to edit record
*
* @return {Promise}
*/
async update(params, data, { files } = {}) {
const existingEntry = await db.query('restaurant').findOne(params);
const isDraft = isDraft(existingEntry, strapi.models.restaurant);
const validData = await strapi.entityValidator.validateEntityUpdate(
strapi.models.restaurant,
data,
{ isDraft }
);
const entry = await strapi.query('restaurant').update(params, validData);
if (files) {
// automatically uploads the files based on the entry and the model
await strapi.entityService.uploadFiles(entry, files, {
model: 'restaurant',
// if you are using a plugin's model you will have to add the `source` key (source: 'users-permissions')
});
return this.findOne({ id: entry.id });
}
return entry;
},
};
params(object): it should look like this{id: 1}
delete
module.exports = {
/**
* Promise to delete a record
*
* @return {Promise}
*/
delete(params) {
return strapi.query('restaurant').delete(params);
},
};
params(object): it should look like this{id: 1}
search
module.exports = {
/**
* Promise to search records
*
* @return {Promise}
*/
search(params) {
return strapi.query('restaurant').search(params);
},
};
params(object): this represent filters for your find request. The object follow the URL query format, refer to this documentation..
{
"name": "Tokyo Sushi"
}
// or
{
"name_contains": "sushi"
}
countSearch
module.exports = {
/**
* Promise to count searched records
*
* @return {Promise}
*/
countSearch(params) {
return strapi.query('restaurant').countSearch(params);
},
};
params(object): this represent filters for your find request. The object follow the URL query format, refer to this documentation..
{
"name": "Tokyo Sushi"
}
// or
{
"name_contains": "sushi"
}
Single Type
find
const _ = require('lodash');
module.exports = {
/**
* Promise to fetch the record
*
* @return {Promise}
*/
async find(populate) {
const results = await strapi.query('restaurant').find({ _limit: 1 }, populate);
return _.first(results) || null;
},
};
populate(array): you have to mention data you want populate["author", "author.name", "comment", "comment.content"]
createOrUpdate
const _ = require('lodash');
module.exports = {
/**
* Promise to add/update the record
*
* @return {Promise}
*/
async createOrUpdate(data, { files } = {}) {
const results = await strapi.query('restaurant').find({ _limit: 1 });
const entity = _.first(results) || null;
let entry;
if (!entity) {
entry = await strapi.query('restaurant').create(data);
} else {
entry = await strapi.query('restaurant').update({ id: entity.id }, data);
}
if (files) {
// automatically uploads the files based on the entry and the model
await strapi.entityService.uploadFiles(entry, files, {
model: 'restaurant',
// if you are using a plugin's model you will have to add the `plugin` key (plugin: 'users-permissions')
});
return this.findOne({ id: entry.id });
}
return entry;
},
};
delete
module.exports = {
/**
* Promise to delete a record
*
* @return {Promise}
*/
delete() {
const results = await strapi.query('restaurant').find({ _limit: 1 });
const entity = _.first(results) || null;
if (!entity) return;
return strapi.query('restaurant').delete({id: entity.id});
},
};
Custom services
You can also create custom services to build your own business logic.
There are two ways to create a service.
- Using the CLI
strapi generate:service restaurant. Read the CLI documentation for more information. - Manually create a JavaScript file named in
./api/**/services/.
Example
The goal of a service is to store reusable functions. An email service could be useful to send emails from different functions in our codebase:
Path — ./api/email/services/Email.js.
const nodemailer = require('nodemailer');
// Create reusable transporter object using SMTP transport.
const transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'user@gmail.com',
pass: 'password',
},
});
module.exports = {
send: (from, to, subject, text) => {
// Setup e-mail data.
const options = {
from,
to,
subject,
text,
};
// Return a promise of the function that sends the email.
return transporter.sendMail(options);
},
};
TIP
please make sure you installed nodemailer (npm install nodemailer) for this example.
The service is now available through the strapi.services global variable. We can use it in another part of our codebase. For example a controller like below:
Path — ./api/user/controllers/User.js.
module.exports = {
// GET /hello
signup: async ctx => {
// Store the new user in database.
const user = await User.create(ctx.query);
// Send an email to validate his subscriptions.
strapi.services.email.send('welcome@mysite.com', user.email, 'Welcome', '...');
// Send response to the server.
ctx.send({
ok: true,
});
},
};
Queries
Strapi provides a utility function strapi.query to make database queries.
You can just call strapi.query('modelName', 'pluginName') to access the query API for any model.
These queries handle for you specific Strapi features like components, dynamic zones, filters and search.
API Reference
find
This method returns a list of entries matching Strapi filters. You can also pass a populate option to specify which relations you want to be populated.
Examples
Find by id :
strapi.query('restaurant').find({ id: 1 });
Find by in IN, with a limit :
strapi.query('restaurant').find({ _limit: 10, id_in: [1, 2] });
Find by date orderBy name :
strapi.query('restaurant').find({ date_gt: '2019-01-01T00:00:00Z', _sort: 'name:desc' });
Find by id not in and populate a relation. Skip the first ten results
strapi.query('restaurant').find({ id_nin: [1], _start: 10 }, ['category', 'category.name']);
findOne
This method returns the first entry matching some basic params. You can also pass a populate option to specify which relations you want to be populated.
Examples
Find one by id :
strapi.query('restaurant').findOne({ id: 1 });
Find one by name :
strapi.query('restaurant').findOne({ name: 'restaurant name' });
Find one by name and creation_date :
strapi.query('restaurant').findOne({ name: 'restaurant name', date: '2019-01-01T00:00:00Z' });
Find one by id and populate a relation
strapi.query('restaurant').findOne({ id: 1 }, ['category', 'category.name']);
create
Creates an entry in the database and returns the entry.
Example
strapi.query('restaurant').create({
name: 'restaurant name',
// this is a dynamiczone field. the order is persisted in db.
content: [
{
__component: 'blog.rich-text',
title: 'Some title',
subTitle: 'Some sub title',
},
{
__component: 'blog.quote',
quote: 'Some interesting quote',
author: 1,
},
],
// this is a component field. the order is persisted in db.
opening_hours: [
{
day_interval: 'Mon',
opening_hour: '7:00 PM',
closing_hour: '11:00 PM',
},
{
day_interval: 'Tue',
opening_hour: '7:00 PM',
closing_hour: '11:00 PM',
},
],
// pass the id of a media to link it to the entry
cover: 1,
// automatically creates the relations when passing the ids in the field
reviews: [1, 2, 3],
});
update
Updates an entry in the database and returns the entry.
Examples
Update by id
strapi.query('restaurant').update(
{ id: 1 },
{
name: 'restaurant name',
content: [
{
__component: 'blog.rich-text',
title: 'Some title',
subTitle: 'Some sub title',
},
{
__component: 'blog.quote',
quote: 'Some interesting quote',
author: 1,
},
],
opening_hours: [
{
day_interval: 'Mon',
opening_hour: '7:00 PM',
closing_hour: '11:00 PM',
},
{
day_interval: 'Tue',
opening_hour: '7:00 PM',
closing_hour: '11:00 PM',
},
],
// pass the id of a media to link it to the entry
cover: 1,
// automatically creates the relations when passing the ids in the field
reviews: [1, 2, 3],
}
);
When updating an entry with its components or dynamic zones beware that if you send the components without any id the previous components will be deleted and replaced. You can update the components by sending their id with the rest of the fields:
Update by id and update previous components
strapi.query('restaurant').update(
{ id: 1 },
{
name: 'Mytitle',
content: [
{
__component: 'blog.rich-text',
id: 1,
title: 'Some title',
subTitle: 'Some sub title',
},
{
__component: 'blog.quote',
id: 1,
quote: 'Some interesting quote',
author: 1,
},
],
opening_hours: [
{
id: 2,
day_interval: 'Mon',
opening_hour: '7:00 PM',
closing_hour: '11:00 PM',
},
{
id: 1,
day_interval: 'Tue',
opening_hour: '7:00 PM',
closing_hour: '11:00 PM',
},
],
// pass the id of a media to link it to the entry
cover: 1,
// automatically creates the relations when passing the ids in the field
reviews: [1, 2, 3],
}
);
Partial update by name
strapi.query('restaurant').update(
{ title: 'specific name' },
{
title: 'restaurant name',
}
);
delete
Deletes an entry and returns its value before deletion. You can delete multiple entries at once with the passed params.
Examples
Delete one by id
strapi.query('restaurant').delete({ id: 1 });
Delete multiple by field
strapi.query('restaurant').delete({ district: '_18th' });
count
Returns the count of entries matching Strapi filters.
Examples
Count by district
strapi.query('restaurant').count({ district: '_1st' });
Count by name contains
strapi.query('restaurant').count({ name_contains: 'food' });
Count by date less than
strapi.query('restaurant').count({ date_lt: '2019-08-01T00:00:00Z' });
search
Returns entries based on a search on all fields allowing it. (this feature will return all entries on sqlite).
Examples
Search first ten starting at 20
strapi.query('restaurant').search({ _q: 'my search query', _limit: 10, _start: 20 });
Search and sort
strapi.query('restaurant').search({ _q: 'my search query', _limit: 100, _sort: 'date:desc' });
countSearch
Returns the total count of entries based on a search. (this feature will return all entries on sqlite).
Example
strapi.query('restaurant').countSearch({ _q: 'my search query' });
Custom Queries
When you want to customize your services or create new ones you will have to build your queries with the underlying ORM models.
To access the underlying model:
strapi.query(modelName, plugin).model;
Then you can run any queries available on the model. You should refer to the specific ORM documentation for more details:
Bookshelf
Documentation: https://bookshelfjs.org/
(opens new window)
Example
const result = await strapi
.query('restaurant')
.model.query(qb => {
qb.where('id', 1);
})
.fetch();
const fields = result.toJSON();
Knex
Knex.js can be used to build and make custom queries directly to the database.
Documentation: http://knexjs.org/#Builder
(opens new window)
You can access the Knex instance with:
const knex = strapi.connections.default;
You can then use Knex to build your own custom queries. You will lose all the functionalities of the model, but this could come handy if you are building a more custom schema. Please note that if you are using the draft system, Strapi nullyfies all the Draft columns util they are published.
Example
const _ = require('lodash');
const knex = strapi.connections.default;
const result = await knex('restaurants')
.where('cities', 'berlin')
.whereNot('cities.published_at', null)
.join('chefs', 'restaurants.id', 'chefs.restaurant_id')
.select('restaurants.name as restaurant')
.select('chef.name as chef')
// Lodash's groupBy method can be used to
// return a grouped key-value object generated from
// the response
return (_.groupBy(result, 'chef');
We strongly suggest to sanitize any strings before making queries to the DB Never attempt to make a raw query with data coming straight from the front-end; if you were looking for raw queries, please refer to this section
(opens new window) of the documentation.
Mongoose
Documentation: https://mongoosejs.com/
(opens new window)
Example
const result = strapi.query('restaurant').model.find({
date: { $gte: '2019-01-01T00.00.00Z' },
});
const fields = result.map(entry => entry.toObject());
Models
Concepts
Content Type‘s models
Models are a representation of the database‘s structure. They are split into two separate files. A JavaScript file that contains the model options (e.g: lifecycle hooks), and a JSON file that represents the data structure stored in the database.
Path — ./api/restaurant/models/Restaurant.js.
module.exports = {
lifecycles: {
// Called before an entry is created
beforeCreate(data) {},
// Called after an entry is created
afterCreate(result) {},
},
};
Path — ./api/restaurant/models/Restaurant.settings.json.
{
"kind": "collectionType",
"connection": "default",
"info": {
"name": "restaurant",
"description": "This represents the Restaurant Model"
},
"attributes": {
"cover": {
"collection": "file",
"via": "related",
"plugin": "upload"
},
"name": {
"default": "",
"type": "string"
},
"description": {
"default": "",
"type": "text"
}
}
}
In this example, there is a Restaurant model which contains the attributes cover, name and description.
Component‘s models
Another type of model is named components. A component is a data structure that can be used in one or many other API‘s model. There is no lifecycle related, only a JSON file definition.
Path — ./components/default/simple.json
{
"connection": "default",
"collectionName": "components_default_simples",
"info": {
"name": "simple",
"icon": "arrow-circle-right"
},
"options": {},
"attributes": {
"name": {
"type": "string"
}
}
}
In this example, there is a Simple component which contains the attribute name. And the component is in the category default.
Where are the models defined?
The Content Types models are defined in each ./api/**/models/ folder. Every JavaScript or JSON file in these folders will be loaded as a model. They are also available through the strapi.models and strapi.api.**.models global variables. Usable everywhere in the project, they contain the ORM model object that they refer to. By convention, a model‘s name should be written in lowercase.
The Components models are defined in the ./components folder. Every component has to be inside a subfolder (the category name of the component).
How to create a model?
TIP
If you are just starting out it is very convenient to generate some models with the Content Type Builder directly in the admin interface. You can then review the generated model mappings on the code level. The UI takes over a lot of validation tasks and gives you a feeling for available features.
For Content Types models
Use the CLI and run the following command strapi generate:model restaurant name:string description:text.
Read the CLI documentation for more information.
This will create two files located at ./api/restaurant/models:
Restaurant.settings.json: contains the list of attributes and settings. The JSON format makes the file easily editable.Restaurant.js: importsRestaurant.settings.jsonand extends it with additional settings and life cycle callbacks.
TIP
When you create a new API using the CLI (strapi generate:api <name>), a model is automatically created.
For Components models
To create a component you will have to use the Content Type Builder from the Admin panel, there is not a cli generator for components.
Or you can create your component manually by following the file path described previously and by following the file structure described below.
Model settings
Additional settings can be set on models:
kind(string) - Define if the model is a Collection Type (collectionType) of a Single Type (singleType) - only for Content Typesconnection(string) - Connection name which must be used. Default value:default.collectionName(string) - Collection name (or table name) in which the data should be stored.globalId(string) - Global variable name for this model (case-sensitive) - only for Content Typesattributes(object) - Define the data structure of your model. Find available options below.
Path — Restaurant.settings.json.
{
"kind": "collectionType",
"connection": "mongo",
"collectionName": "Restaurants_v1",
"globalId": "Restaurants",
"attributes": {}
}
In this example, the model Restaurant will be accessible through the Restaurants global variable. The data will be stored in the Restaurants_v1 collection or table and the model will use the mongo connection defined in ./config/database.js
WARNING
If not set manually in the JSON file, Strapi will adopt the filename as globalId. The globalId serves as a reference to your model within relations and Strapi APIs. If you chose to rename it (either by renaming your file or by changing the value of the globalId), you‘d have to migrate your tables manually and update the references. Please note that you should not alter the Strapi’s models globalId (plugins and core models) since they are used directly within Strapi APIs and other models’ relations.
TIP
The connection value can be changed whenever you want, but you should be aware that there is no automatic data migration process. Also if the new connection doesn‘t use the same ORM you will have to rewrite your queries.
Model information
The info key on the model-json states information about the model. This information is used in the admin interface, when showing the model.
name: The name of the model, as shown in admin interface.description: The description of the model.icon: The fontawesome V5 name - only for Components
Path — Restaurant.settings.json.
{
"info": {
"name": "restaurant",
"description": ""
}
}
Model options
The options key on the model-json states.
-
timestamps: This tells the model which attributes to use for timestamps. Accepts eitherbooleanorArrayof strings where first element is create date and second element is update date. Default value when set totruefor Bookshelf is["created_at", "updated_at"]and for MongoDB is["createdAt", "updatedAt"]. -
privateAttributes: This configuration allows to treat a set of attributes as private, even if they‘re not actually defined as attributes in the model. Accepts anArrayof strings. It could be used to remove from API responses timestamps or_vwhen using MongoDB. The set ofprivateAttributesdefined in the model are merged with theprivateAttributesdefined in the global Strapi configuration. -
populateCreatorFields: Configure whether the API response should includecreated_byandupdated_byfields or not. Accepts aboolean. The default value isfalse. -
draftAndPublish: Enable the draft and publish feature. Accepts aboolean. The default value isfalse.
Path — Restaurant.settings.json.
{
"options": {
"timestamps": true,
"privateAttributes": ["id", "created_at"],
"populateCreatorFields": true,
"draftAndPublish": false
}
}
Define the attributes
The following types are currently available:
stringtextrichtextemailpasswordintegerbigintegerfloatdecimaldatetimedatetimebooleanenumerationjsonuid
Validations
You can apply basic validations to attributes. The following supported validations are only supported by MongoDB database connections. If you‘re using SQL databases, you should use the native SQL constraints to apply them.
required(boolean) — If true, adds a required validator for this property.unique(boolean) — Whether to define a unique index on this property.index(boolean) — Adds an index on this property, this will create a single field index
(opens new window) that will run in the background. Only supported by MongoDB.max(integer) — Checks if the value is greater than or equal to the given maximum.min(integer) — Checks if the value is less than or equal to the given minimum.
Security validations
To improve the Developer Experience when developing or using the administration panel, the framework enhances the attributes with these “security validations”:
private(boolean) — If true, the attribute will be removed from the server response. (This is useful to hide sensitive data).configurable(boolean) - If false, the attribute isn‘t configurable from the Content Type Builder plugin.autoPopulate(boolean) - If false, the related data will not populate within REST responses. (This will not stop querying the relational data on GraphQL)
Exceptions
uid
targetField(string) — The value is the name of an attribute that hasstringof thetexttype.options(string) — The value is a set of options passed to the underlyinguidgenerator
(opens new window). A caveat is that the resulting uidmust abide to the following RegEx/^[A-Za-z0-9-_.~]*$.
Example
Path — Restaurant.settings.json.
{
...
"attributes": {
"title": {
"type": "string",
"min": 3,
"max": 99,
"unique": true
},
"description": {
"default": "My description",
"type": "text",
"required": true
},
"slug": {
"type": "uid",
"targetField": "title"
}
...
}
}
Relations
Relations let you create links (relations) between your Content Types.
One-way relationships are useful to link one entry to one other entry. However, only one of the models can be queried with its linked item.
Example
A pet can be owned by someone (a user).
Path — ./api/pet/models/Pet.settings.json.
{
"attributes": {
"owner": {
"model": "user"
}
}
}
Example
``` // Create a pet const xhr = n
(本文超出站点单文档体积上限,已截断)
