POSTS
Duolingo-clone within 2 evenings via Firebase
By slnt_opp
Once upon a time i had an idea: make a database and authentication gateway - service, which would be accessible as API only, to make it possible to create dynamic web-apps without backend. This idea has been bought by Google, not from me ofcourse, cause i haven’t done anything :). But let’s talk about this another time, today let’s try to get little but into Firebase and find out how to use it and should you use it.
Little about web-apps architecture
Let’s try to look on web from like above. If we would, we would have three well-known ends:
- User interface a.k.a. front-end
- Business logic a.k.a. back-end
- Database a.k.a.
Mong
This is a consequence of us having 3 basic problems to solve:
- Understand what’s the user problem
- Solve the users problem
- Explain user, that’s problem is solver
(Order is reversed)
And anyway any app is built like this.
But due to evolution of browsers and JS itself, intefaces went quite far, and majority of public apps have no unqie logic, which have to be hidden behind the backend. But backend is the binding with DB as well.
Soooo…
Without server - how?
Server is not going anywhere, it’s just less servers or servers getting smaller, or more often it’s just not your headache anymore. That began i don’t know when, but became very popular by spreading of UI technologies and graph-databases, like DGraph(kind of which Firebase is using). What this graph DBs are? We can speak a lot about math laying under them, but the important facts for us here are security and principled impossibility of unneeded data leaks.
Achtung! It’s my opinion, understanding and observations, i’m not a “db-sciencist” or mathematician This kind of database is a multidimensional graph, where by going vertically we’re going from user to user, and by orthogonal movement we’re reading data. And links between node have directions, which means that if we have the following graph(Letters - users, Digits - data):
R # root
/ \
0 - D A - 0 - 1 - 2
| |
0 - E - B - 0
| |
F C - 0 - 1
|
.................
So, if you’re using credentials for user B, you can get an access to C and C’s data, because C is under, to E and it’s data because there is the manually added link, and F, because F is under E, and so on. But you can’t get A. noway. So for B, observable graph would be:
0 - E - B - 0
| |
F C - 0 - 1
|
.................
Also, this kind of DBs have rules systems defined by users. Why is it important? Two things:
- By default everything is prohibided, rules are allowing classes(collections) and objects(docs) separately
- По умолчанию все запрещено, правила разрешают все классы и методы по отдельности
- You can compare request and document data
So you can publish data, you can send requests to DB without authorization and send back Permission denied
error. Because most of the rules beginning with if request.auth
, except one - creating users.
Yes, creating account in DB in my and simillar cases will be available for everybody - users just have to use one of given auth drivers. So the DB lives its life, without you, and lives nice and secure.
Why’d we need it? We can make the whole logic on front-end and using GraphQL make the full app.
Firebase
Firebase is the logicful consequence of this kind of technologies existance. Firebase consists of 7 services, let’s go one by one.
Authentication
This service solves the user-creating problem, after lil setup user won’t register, write, read or delete any data without providing the token from one of auth providers. Also, Firebase provides Firebase UI, which can do something else, but basically it’s a container with buttons and cookies writer for different providers, which are: Google, Apple, Facebook, Twitter, GitHub, Microsoft, Yahoo, Phone and classical email/pass.
Cloud Firestore and Realtime Database
These are two services for storeing data. Both are NoSQL. Access is vie API and/or libraries. Difference is on price and functionality ofcourse. Basically Firestore is just NoSQL like MongoDB, Realtime stores pure JSON and has features like updates hooks and so on, that’s why it’s often being used for games and messaging. You can understand the difference better by going through poll-helper at Firestore page.
Storage
Nothing to say here - this is CDN. Put, take, quick - everywhere. Тут нечего рассказывать - это CDN. Клади, забирай, быстро во всем мире.
Hosting
Hosting works GitHub Pages like - only “static” generated apps, they are being putted to CDN and being served as is. So you can put there any app made with modern framework like Vue, Angular, React etc.
Functions
If you still need to hide some parts of you logics, you can use Functions. Actually you’re just writting you snippet with JS and it’s being auto-compile into web-server and works somewhere. Functions being invoked by simple http queries.
Machine Learning
That’s quite obvious, Google just brings the power of their ML Kit your app, and you don’t need to increase the load on client side with self-writtten models on Tensorflow.js. ML gives you pretrained ready to use models like barcode-scanners, translator and smart-replies.
You can use all collected data from Firestore for building and training models as well.(Just check GDPR first pls)
Nice.
Let’s do some practice
Example by copying Duolingo
If somebody doesn’t know
Duolingo is the one of many, but seems to be the most popular/PRd, service for languages self-study. User choses nativ language, language user want to learn and goes through lessons in playing form with increasing complexity.
How effective it is - is not really easy to say, but it helped me much times to get some basic knowledge and traveller phrases. My peak was the 5 sentences long conversation with joke in spanish, which is as i think an absolute maximum i can ask from free app.
Tasks are splitted into 5 types:
- Choose word by pictures
- Translate sentence - by writting it
- Translate sentence - by making it from given words
- Fill the gap with word from given options
- Read the sentence loud(optional)
Tasks number 2 and 3 working bi-directional(translate from foreign to native)
What was the request
My gf asked me for an utility, to easier prepare for letter-writting(part of exam) in german. It’s quite often for us, i’ve already made her an utility for learing acids years back.
What was the goal
Make Duolingo-like UX, without increading the load on my server, so to try to do this with Firebase.
What i have done
Actually i’ve done what i’ve wanted, but as soon as the deadline was really close(exam is soon, so as tracker says i spent 7 hours, which is two evenings). I’ve cherry-picked only two options of tasks - 2, because that is what she needs for letter, and 3-like as a hint, but i haven’t finished it.
I have no division to lessons ofcourse, i’m not a teacher or smth and can’t plan it like this, but it’s provided in logics and model :)
So the session lifecycle is:
For user:
- Log in ->
- Choose lesson setup ->
- Answer the questions ->
- Get the results
Technically:
- Log in user vie Google, i.e. get UID ->
- Get tasks by given conf(amount of tasks, type, complexity) ->
- Compare given answer and correct answer better than just
===
-> - Write the result to stats collection ( -> ) extra-point show average mark and fancy progress chart at dashboard
Try it
So, it works, and even develops bit, i’ve spent 4 hours more to fix some bugs and add little features.
You can even try it buy yourself, but aware: it’s not translated to english and lesson won’t stop until all questions are not answered correctly.
App is here by link
Achtung! App is not optimized for small screens, so pls fullscreen only
Screenshots(most of them are outdated, sorry):
What i haven’t told
I think i told enough, to make it bit clear, wth is Firebase and answered the questions i’ve asked myself. But this section is already declared, so couple cons of Firebase:
Firebase Interface is not really suitable to work with DB
Why it should be? Cause it’s needed sometimes. And basically you’ll have to impement MongoDB Compass everytime. In original UI you can read only one doc at once. It is made so, because Google thinks about your data usage, but they could come up with something, i think.
Firebase.js и Firebase UI
Basically both are quite outdated - frameworks integration is headache, callbackhell etc.
Procedures
Их отсутствие скорее. Очень актуальный для моего кейса вопрос, это процедуры в БД. Мое приложение начинается с получения определенного количества случайных заданий, но мне приходится сначала получить все, что может быть очень больно для моего бесплатного плана.
Okaay, one pro
It’s free. Spark free plan is really enough to walk through all milestones until you get investments. Just for 0$.
Conclusion
It’s a nice service, especially to make, deploy and publish prototype quick, which is practicaly prooven. And after you can really easy scale.
Thanks for reading and have a nice use!