2017-10-10 11:15:24 +02:00
# Services
2017-10-11 12:47:01 +02:00
See the [services concept ](../concepts/concepts.md#services ) for details.
2017-10-10 11:15:24 +02:00
## How to create a service?
There is two ways to create a service.
2019-11-07 12:05:39 +01:00
- Using the CLI `strapi generate:service user` . Read the [CLI documentation ](../cli/CLI.md ) for more information.
- Manually create a JavaScript file named `User.js` in `./api/**/services/` .
2017-10-10 11:15:24 +02:00
#### Example
2017-10-12 13:00:07 +02:00
The goal of a service is to store reusable functions. An `email` service could be useful, if we plan to send emails from different functions in our codebase:
2017-10-10 11:15:24 +02:00
**Path —** `./api/email/services/Email.js` .
2019-11-07 12:05:39 +01:00
2017-10-10 11:15:24 +02:00
```js
const nodemailer = require('nodemailer');
// Create reusable transporter object using SMTP transport.
const transporter = nodemailer.createTransport({
2017-10-11 10:51:28 +02:00
service: 'Gmail',
auth: {
user: 'user@gmail .com',
2019-11-07 12:05:39 +01:00
pass: 'password',
},
2017-10-10 11:15:24 +02:00
});
module.exports = {
2019-11-07 12:05:39 +01:00
send: (from, to, subject, text) => {
2017-10-10 11:15:24 +02:00
// Setup e-mail data.
const options = {
from,
to,
subject,
2019-11-07 12:05:39 +01:00
text,
2017-10-10 11:15:24 +02:00
};
// Return a promise of the function that sends the email.
return transporter.sendMail(options);
2019-11-07 12:05:39 +01:00
},
2017-10-10 11:15:24 +02:00
};
```
2019-11-07 12:05:39 +01:00
::: tip
2018-10-01 12:19:34 +02:00
please make sure you installed `nodemailer` (`npm install nodemailer` ) for this example.
:::
2017-10-10 11:15:24 +02:00
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` .
2019-11-07 12:05:39 +01:00
2017-10-10 11:15:24 +02:00
```js
module.exports = {
// GET /hello
2019-11-07 12:05:39 +01:00
signup: async ctx => {
2017-10-10 11:15:24 +02:00
// Store the new user in database.
const user = await User.create(ctx.params);
// Send an email to validate his subscriptions.
2019-11-07 12:05:39 +01:00
strapi.services.email.send(
'welcome@mysite .com',
user.email,
'Welcome',
'...'
);
2017-10-10 11:15:24 +02:00
// Send response to the server.
ctx.send({
2019-11-07 12:05:39 +01:00
ok: true,
2017-10-10 11:15:24 +02:00
});
2019-11-07 12:05:39 +01:00
},
2017-10-10 11:15:24 +02:00
};
```