Being in a restaurant, the first thing that gets presented to you is the menu. This action repeatedly happens whenever you go to a restaurant. In the same vein, so many events or activities get repeated in software engineering. Therefore, it is nice that we employ the DRY (Don't Repeat Yourself) concept all the time to make things easier.
To follow this article, you’ll need:
These two concepts relate. Controllers are where actions are stored. These actions get triggered when a client requests a particular route defined in the code. Controllers are responsible for controlling the flow of any application that follows the MVC framework,
including Strapi.
Services help you with the DRY principle, as they do what they even mean; they serve. These are reusable functions that simplify controllers' logic.
Whenever you create a new content type or model, Strapi generates a new service file that does nothing but could override the generic service created in the node_module.
Let's spin up a project by creating a new application if you don't have one already.
npx create-strapi-app@latest my-project --quickstart
//Or
yarn create strapi-app my-project --quickstart
After installation, navigate to http://localhost:1337/admin
and complete the form to create the first Administrator user.
First, we will create an API with its configurations, controller, and service.
npm run strapi generate
Then do the following.
api
as the generator.comment
for the name.n.
Your selections should look like the screenshot below:
Next, generate a content-type with the Strapi generate command below:
npm run strapi generate
We want this content type to have two fields: user and description. So your selection should look like the screenshot below:
Your codebase should look like this:
The above command will create an empty collection called Comments.
We want to use the Service Strapi generated to send SMS when a user creates a new comment. However, we can achieve endless possibilities of functionalities with the Strapi Generated Services.
Create a file called sms.js
in the ./api/comment/services
folder and add paste this code to it:
1 'use strict';
2 module.exports = {};
We will send an SMS whenever a user creates a comment using Twilio. Let's install Twilio using the following command:
Log in to Your Twilio Account or create one if you don't already have it here. Now, copy out your ACCOUNT SID
and AUTH TOKEN.
Paste the following in the .env
file located in ./env
:
1TWILIO_ACCOUNT_SID = AC82a29b91a67xxxxxxxxx
2TWILIO_AUTH_TOKEN = 81682479468249xxxxxxxxxxx
3MYNUM = +23490xxxxxxx
4TWILIONUM = +16463xxxxxx
Where AC82a29b91a67xxxxxxxxx
is your exact ACCOUNT SID
and 81682479468249xxxxxxxxxxx
is the same AUTH TOKEN
you copied from your Twilio account. TWILIONUM
will be the exact phone number given by Twilio, and MYNUM
should be the destination number.
Then we will create a function that will be exported and be globally accessible through the strapi.services
.
In our service file at ./api/comment/services/sms.js
:
1 module.exports = {
2 sendSms() {
3 const accountSid = process.env.TWILIO_ACCOUNT_SID;
4 const authToken = process.env.TWILIO_AUTH_TOKEN;
5 const myNum = process.env.MYNUM;
6 const twilioNum = process.env.TWILIONUM;
7 const client = require("twilio")(accountSid, authToken);
8 client.messages
9 .create({
10 body: "Hello Admin, someone just posted a comment",
11 from: twilioNum, //the phone number provided by Twillio
12 to: myNum, // your own phone number
13 })
14 .then((message) => console.log(message.sid));
15 },
16 };
Now let us go to the ./api/comment/controllers/comment.js
and define what will happen whenever a user comments on our application.
In our ./api/comment/controllers/comment.js
, we will call the global strapi.services
and other methods we created in ./api/comment/services/sms.js.
1 module.exports = {
2 async create(ctx) {
3 strapi.service("api::comment.sms").sendSms();
4 return await strapi
5 .service("api::comment.comment")
6 .create(ctx.request.body);
7 },
8
9 async get(ctx) {
10 return await strapi
11 .service("api::comment.comment")
12 .get(ctx.request.body);
13 },
14 }
Whenever we make a post request in Comments collections, it calls the Customs Service, which communicates to the Twilio server and sends us an SMS. Now create the create
service in ./api/comment/service/comment.js
to save the actual comment to our collection.
1 "use strict"
2 module.exports = () => ({
3 async create(data) {
4 return await strapi.entityService.create("api::comment.comment", {
5 data,
6 });
7 },
8
9 async get() {
10 return await strapi.entityService.findMany("api::comment.comment");
11 },
12 });
13
14Finally, configure a route for our `create` service in `./api/comment/routes/comment.js` with the code snippet below:
15
16
17 module.exports = {
18 routes: [
19 {
20 method: "POST",
21 path: "/comment",
22 handler: "comment.create",
23 config: {
24 policies: [],
25 middlewares: [],
26 },
27 },
28 {
29 method: "GET",
30 path: "/comment",
31 handler: "comment.get",
32 config: {
33 policies: [],
34 middlewares: [],
35 },
36 },
37 ],
38 };
We can test whether or not the SMS will be delivered when we try to create a new comment by making a post request. Make sure you have the create access in your application role by navigating to Settings->USERS & PERMISSIONS PLUGIN->Roles-> Public
:
So we will be using Postman to send a POST
request to this URL http://localhost:1337/comments. Fill in the following JSON data in the request body and hit the Send button.
1 {"user": "Precious",
2 "description": "I just want to comment that Strapi is dope"}
You should also receive the SMS delivered to your phone number.
Next, we will talk about how to send emails using custom services. We will try to notify ourselves when a product is added to the collection. We should get notified through email.
Let's create a new API for that:
npm run strapi generate
The command will create a new folder in ./api/
called product
with the following sub-folders routes, services
controllers.
We will use a package called nodemailer.
So make sure you install it using the command below.
npm install nodemailer
Let's create another collection for our product API with the generate command.
npm run strapi generate
Now, paste the following codes in the service of our just created product found in ./api/product/services/product.js.
1 const toEmail = process.env.TOEMAIL;
2 const welcome = process.env.WELCOME;
3 module.exports = {
4 async create(data) {
5 const response = await strapi.entityService.create("api::product.product", {
6 data,
7 });
8 strapi
9 .service("api::comment.sendmail")
10 .send(
11 welcome,
12 toEmail,
13 "Welcome",
14 `A product has been created ${entity.name}`
15 );
16 return response;
17 },
18 };
Next, create a controller for the create
service in the ./api/product/controllers/product.js
file with the code below:
1 module.exports = {
2 async create(ctx) {
3 return await strapi
4 .service("api::prooduct.prooduct")
5 .create(ctx.request.body);
6 },
7 };
Then configure the route in the ./api/product/routes/product.js
file with the code below:
1 module.exports = {
2 routes: [
3 {
4 method: 'POST',
5 path: '/product',
6 handler: 'product.create',
7 config: {
8 policies: [],
9 middlewares: [],
10 },
11 },
12 ],
13 };
Ensure you have the create access in your application role in the product(Settings->USERS & PERMISSIONS PLUGIN->Roles-> Public
). And of course, all your environment variable (TOEMAIL
and WELCOME
) are defined in the .env
file.
Create asendmail.js
file in ./api/sendmail/services/
and add the code below:
1 const nodemailer = require('nodemailer');
2 const userEmail = process.env.MYEMAIL
3 const userPass = process.env.MYPASS
4 // Create reusable transporter object using SMTP transport.
5 const transporter = nodemailer.createTransport({
6 service: 'Gmail',
7 auth: {
8 user: userEmail,
9 pass: userPass,
10 },
11 });
12 module.exports = {
13 send: (from, to, subject, text) => {
14 // Setup e-mail data.
15 const options = {
16 from,
17 to,
18 subject,
19 text,
20 };
21 // Return a promise of the function that sends the email.
22 return transporter.sendMail(options);
23
24 },
25 };
Also, define all your environment variables (MYEMAIL
and MYPASS
) in the .env
file.
This is your Gmail email address and the password to access it. Unfortunately, for our app to have access to our email, we need to lessen the security of Gmail a little bit. This is because Google does not let third-party applications access its accounts without approvals.
Go to your Google Accounts and put ON less secure app access.
Next, create a controller for our product API's create
service.
Now we will create a new product in Postman(HTTP Client). Send a Post
request to this URL http://localhost:1337/products. Add the JSON data below to the request body:
1{
2"name": "A headphone",
3"price": 2000
4}
When you hit the Send button, you should get this response below if everything goes successfully:
1{
2 "id": 5,
3 "name": "A headphone",
4 "price": 2000,
5 "createdAt": "2022-05-05T12:23:09.965Z",
6 "updatedAt": "2022-05-05T12:23:09.965Z"
7}
You should also get a notification on your email like below if everything goes successfully:
This Email Notification task is just a tip of what you can achieve with Strapi Services. The use case of Services is limitless. You can do any business logic.
Now, what's this whole concept of services in Strapi without an actual example of how it works? So I will be using Reactjs to show you one of the many ways services in Strapi work. Let's move away from our current Strapi project. Instead, we will create a new application with create-react-app.
In a different directory, run this command to create a new React app:
npx create-react-app strapicomment
I decided to call my application strapicomment ( you can call yours anything). After our react application has been created, let's move into its directory and start the application.
cd strapicomment
yarn start
The above command will set up our React application, and it will start on http://localhost:3000/.
Next, open the codebase in any code editor of your choice. I will be using VSCode for this example:
We will clean up the project and remove some unnecessary codes with React Quickstart boilerplate. In the src folder, delete the logo.svg, and create a folder called components (which is where all our components will be going).
Next, copy and paste this code to replace the existing code in App.js
:
1 function App() {
2 return (
3 <div className="App">
4 <h1>Hello React</h1>
5 </div>
6 );
7 }
8 export default App;
Let’s create three components in .src/components
namely Form.js, List.jsx
, and Comment.jsx
In our Form.js
, paste in the following codes.
1 import React, { Component } from "react";
2 export default class Form extends Component {
3 constructor(props) {
4 super(props);
5 this.state = {
6 loading: false,
7 error: "",
8 comment: {
9 user: "",
10 description: ""
11 }
12 };
13 // bind context to methods
14 this.handleFieldChange = this.handleFieldChange.bind(this);
15 this.onSubmit = this.onSubmit.bind(this);
16 }
17 /**
18 * Handle form input field changes & update the state
19 */
20 handleFieldChange = event => {
21 const { value, name } = event.target;
22 this.setState({
23 ...this.state,
24 comment: {
25 ...this.state.comment,
26 [name]: value
27 }
28 });
29 };
30 /**
31 * Form submit handler
32 */
33 onSubmit(el) {
34 // prevent default form submission
35 el.preventDefault();
36 if (!this.isFormValid()) {
37 this.setState({ error: "All fields are required." });
38 return;
39 }
40 // loading status and clear error
41 this.setState({ error: "", loading: true });
42 // persist the comments on server
43 let { comment } = this.state;
44 fetch("http://localhost:1337/api/comment", {
45 headers:{'Content-type':'application/json'},
46 method: "post",
47 body: JSON.stringify(comment)
48 })
49 .then(res => res.json())
50 .then(res => {
51 if (res.error) {
52 this.setState({ loading: false, error: res.error });
53 } else {
54 this.props.addComment(comment);
55
56 this.setState({
57 loading: false,
58 comment: { ...comment, description: "" }
59 });
60 }
61 })
62 .catch(err => {
63 this.setState({
64 error: "yo! something is sideways",
65 loading: false
66 });
67 });
68 }
69 /**
70 * Simple validation
71 */
72 isFormValid() {
73 return this.state.comment.user !== "" && this.state.comment.description !== "";
74 }
75 renderError() {
76 return this.state.error ? (
77 <div className="alert alert-danger">{this.state.error}</div>
78 ) : null;
79 }
80 render() {
81 return (
82 <React.Fragment>
83 <form method="post" onSubmit={this.onSubmit}>
84 <div className="form-group">
85 <input
86 onChange={this.handleFieldChange}
87 value={this.state.comment.user}
88 className="form-control"
89 placeholder="UserName"
90 name="user"
91 type="text"
92 />
93 </div>
94 <div className="form-group">
95 <textarea
96 onChange={this.handleFieldChange}
97 value={this.state.comment.description}
98 className="form-control"
99 placeholder="Your Comment"
100 name="description"
101 rows="5"
102 />
103 </div>
104 {this.renderError()}
105 <div className="form-group">
106 <button disabled={this.state.loading} className="btn btn-primary">
107 Comment ➤
108 </button>
109 </div>
110 </form>
111 </React.Fragment>
112 );
113 }
114 }
I am using bootstrap for basic styling. I decided to bring it in through CDN, so go to the public folder in your root and locate index.html
and paste this in between your head tags:
1 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
2 integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"
3 crossorigin="anonymous">
In our List.jsx
, paste in the following codes.
1 import React from "react";
2 import Comment from "./Comment";
3 export default function List(props) {
4 return (
5 <div className="commentList">
6 <h5 className="text-muted mb-4">
7 <span className="badge badge-success">{props.comments.length}</span>{" "}
8 Comment{props.comments.length > 0 ? "s" : ""}
9 </h5>
10 {props.comments.length === 0 && !props.loading ? (
11 <div className="alert text-center alert-info">
12 Be the first to comment
13 </div>
14 ) : null}
15 {props.comments.map((comment, index) => (
16 <Comment key={index} comment={comment} />
17 ))}
18 </div>
19 );
20 }
What we are doing here is mapping through and displaying the available comments. If there is none, you will be the first to comment.
In our Comment.jsx
, paste in the following codes.
1 import React from "react";
2 export default function Comment(props) {
3 const { user, description } = props.comment;
4 return (
5 <div className="media mb-3">
6 <div className="media-body p-2 shadow-sm rounded bg-light border">
7 <h6 className="mt-0 mb-1 text-muted">{user}</h6>
8 {description}
9 </div>
10 </div>
11 );
12 }
Back to App.js
in the src folder, replace it with the codes below.
1 import React, { Component } from "react";
2 import List from "./components/List";
3 import Form from "./components/Form";
4 class App extends Component {
5 constructor(props) {
6 super(props);
7 this.state = {
8 comments: [],
9 loading: false
10 };
11 this.addComment = this.addComment.bind(this);
12 }
13 componentDidMount() {
14 // loading
15 this.setState({ loading: true });
16 // get all the comments
17 fetch("http://localhost:1337/api/comment")
18 .then(res => res.json())
19 .then(res => {
20 this.setState({
21 comments: res,
22 loading: false
23 });
24 })
25 .catch(err => {
26 this.setState({ loading: false });
27 });
28 }
29
30 addComment(comment) {
31 this.setState({
32 loading: false,
33 comments: [comment, ...this.state.comments]
34 });
35 }
36 render() {
37
38 return (
39 <div className="App container bg-light shadow">
40
41 <div className="row">
42 <div className="col-4 pt-3 border-right">
43 <h6>Speak your Truth</h6>
44 <Form addComment={this.addComment} />
45 </div>
46 <div className="col-8 pt-3 bg-white">
47 <List
48 loading={this.state.loading}
49 comments={this.state.comments}
50 />
51 </div>
52 </div>
53 </div>
54 );
55 }
56 }
57 export default App;
We have successfully created our application. Whenever a user comments, we get notified through SMS. We can do the same with email or any functionality across our minds.
The code for both the React App and the Strapi backend is available here.
Strapi services offer a whole lot of benefits, and that makes developing easy. We have seen how this works in the little application that sends SMS using Twillio API whenever a user comments on our application. We have also seen how to create email notifications with Strapi Services.
I am Software Engineer and Technical Writer. Proficient Server-side scripting and Database setup. Agile knowledge of Python, NodeJS, ReactJS, and PHP. When am not coding, I share my knowledge and experience with the other developers through technical articles