We don’t need alot of work to set up our API anymore we can focus on others fun stuff, let’s make thing goes real time with strapi & socket.io !
Before starting strapi you can do
npm ls strapi which print something like this :
firstname.lastname@example.org /path/to/project/strapi_socket └── email@example.com
So you know where is the strapi used and we can see this is the local strapi inside our project’s node_modules and not the global version. We can now start strapi by running.
Don’t forget to start mongoDB (
mongo on your terminal before starting strapi).
Add new model
In a few steps I will create a simple model named bakery from the content type builder tab :
And give it two fields :
nameis a string
ratingis an integer
IMPORTANT: don’t forget to click save !!!
Strapi will create this folder structure inside your project, those folders are self explanatory config, controllers, models, services … We can use them to do more, like add some logique inside the controller, that is exactly what we will do later.
Setup users permissions for guest role (not logged in) to read/create bakery entries, go back to admin panel on tab Users & Permissions tab. Click on Guest role, on application check create & find and don’t forget to click save !
View data at /bakery it should render an empty array
config/functions/bootstrap.js and create
public/bakery.html add this two code then reload your page, to see the log inside developper console like this :
Now let’s modify our html to create new bakery entries from our bakery.html file with this code, after changing our code reload and set both name and rating value before submit with the add button.
You can check that the entry has been saved by checking /bakery api url with GET method, it should respond with an non empty array this time.
Yummy ! we stored our first bakery inside our mongoDB storage !
Again we are going to make some code change, inside
config/functions/bootstrap.js write this code, after that open our auto generated api controller for bakery entries
api/bakery/controllers/Bakery.js, on ligne 47 there is the method that is called when a user create a bakery item
We will call our
emitToAllUsers() function from strapi that we defined on
config/functions/bootstrap.js, inside create method add this line.
At the end of our script tag inside
public/bakery.html listen fo the food_ready event, add a
div#food on your html plus some JS, open two or more tab (i’m gonna use one chrome tab and one firefox tab) to test it, and play with both to see that both users get notified when someone save some sweet on our API.
That’s all, with this quick intro on how to use strapi & socket.io we can image doing things like chat app, html5 online multiplayer games etc …