Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🤓 This is a simple SPA built using Koa as the backend, Vue as the first frontend, and React as the second frontend. Features MySQL integration, user authentication, CRUD note actions, and async/await.

License

NotificationsYou must be signed in to change notification settings

johndatserakis/koa-vue-notes-api

Repository files navigation

   

LicenseTweet

Koa-Vue-Notes-Api

This is a simple SPA built usingKoa as the backend,Vue as the first frontend, andReact as the second frontend.

Features

  • Koa 2.5.1
  • Fully written using async/await
  • Koa-Router
  • Koa-Ratelimit
  • Koa-Bodyparser
  • KCors
  • Koa-Json-Error for JSON requests/responses
  • Koa-Useragent to get client user-agent data
  • Bcrypt
  • Sendgrid Mailer for email
  • Joi for input validation
  • Fs-Extra
  • JWT
  • Nodemon for running in development
  • Prettier
  • Babel
  • MySQL
  • Knex with migrations and seeds
  • Jest for testing
  • Faker to create seeds
  • log4js for logging
  • Docker server
  • And more...

Installing / Getting started

# Install dependenciesnpm i# Serve using nodemon with hot reloadnpm run watch# Build for productionnpm run build# Lint the project with eslintnpm run lint# Run testsnpm runtest## knex Migrations## Note - All knex migrate/rollback/seed calls must be prefaced## with the setting of NODE_ENV - also, seeds and rollbacks are## disabled in production# Migrate latestNODE_ENV=development knex migrate:latest# RollbackNODE_ENV=development knex migrate:rollback# Run all seedsNODE_ENV=development knex seed:run# Make migrationknex migrate:make create_users_table# Make seedknex seed:make seed_users

Note

If you want to turn on the rate-limiter, uncomment the rate-limiter block in./src/index.js and make sure you have redis running. I use homebrew. You can followthis guide. After installing and running redis, you should be able to enterredis-cli ping into a terminal and getPONG back.

General Information

This backend is part of a pair of projects that serve a simple notes app. I chose a notes app because it gives you a good look at the different techniques used in both the frontend and backend world. What's really cool is these projects feature a fully fleshed-out user login/signup/forgot/reset authentication system usingJWT.

I've liberally commented the code and tried to balance the project in a way that it's complex enough to learn from but not so complex that it's impossible to follow. It can be tough to learn from a boilerplate that has too much or too little.

Having used mainlyPHP for the backend in the past - I am very glad I checked out Koa as I think it is absolutely awesome in the way it handles the server code. Same thing withVue andReact - I've used mainlyjQuery in the past - albeit with the really structured Revealing-Module-Pattern - and usingVue andReact was such a pleasure. You can really tell right away what kind of power a well-structured library can give you.

You'll need to create a.env file and place it in the root of your directory. Take a look at.example.env and add your information as needed. ForJWT_ACCESS_TOKEN_EXP you can set it to5m,5w,5d etc - although5m is what I'm using at the moment. Note - we don't set theNODE_ENV variable in the.env - we set it in the npm scripts. This lets us specifically set different environments as needed. Also make sure to set theJWT_SECRET variable - something random around 32 characters.

This project only responds and listens inJSON. Keep that in mind when send requests throughInsomnia or your frontend.

User Authentication Process

As mentioned in the frontend code, the user authentication process is this:

  • User create an account
  • User logs in
  • The server sends andaccessToken and arefreshToken back
  • We take theaccessToken and decode it usingjwt-decode. This gets us the logged in user's information. We stick this in the Vuex/Reduxuser store. Then we store therefreshToken andaccessToken in the user'slocalStorage.
  • Each protected endpoint will be expecting you to attach theaccessToken you have to the call (usingAuthentication: Bearer)
  • After a short amount of time, the server will respond with401 TOKEN EXPIRED. When you see this - that means you need to send yourrefreshToken anduser.email to the endpoint that deals withaccessToken refreshing.
  • Once you do that, you'll received a brand newaccessToken andrefreshToken
  • Repeat the process as needed

Thesrc folder is the heart of the program. I'll go over its subfolders now.

Controllers

We use controllers to keep our router thin. The controller's responsibility is to manage the request body and make sure it's nice and clean when it eventually gets sent to amodel to make database calls. There are two controller files present - one for user signup/login/forgot... and one for notes. Note: theUserActionController.js is a little different then normal controllers, as I believe the actions of a user signup/login/forgot/reset are seperate from the normal actions for a user - so that's whyUserActionController.js in written in a moreprocedural way.

DB

Here is our database setup. This project usesKnex to manage migrations and execute queries. I initially wrote wrote all theMySQL calls using rawSQL, but the need for a migrations manager pushed me towards anORM for theMySQL database.Knex is awesome - very powerful, easy to use and make queries, and the migrations are nice to have for sure - especially for testing.

For this project you'll need to make two databases in your development environment,koa_vue_notes_development andkoa_vue_notes_testing. In your production environment you would just havekoa_vue_notes_production. Tests use a different database because the data there is extremely volatile - as table information is created and destroyed on every test. Theknexfile.js used here dynamically attaches to the proper database based theNODE_ENV.

Theknexfile.js in the root of the project is all setup with the ability to read your.env file. Make sure to have knex installed globally,npm install -g knex. Let's say you download this project - first you'llnpm i, then create akoa_vue_notes_development database and akoa_vue_notes_testing database, thenknex migrate:latest andknex seed:run to create and seed your tables. Currently it's set up to make five users and 100 notes distributed to those users.

Docker

Docker is used for the development virtual machine and for building the production app. To use the included dockerfile.yml, rundocker-compose up -d --build to bring up the machine. To stop the machine, rundocker-compose down. The main reason docker is used in this case is to host theMySQL database. Make a database namedkoa-vue-notes_development. Connect through Sequel Pro usinghost: 127.0.0.1,port: 3360,user: root, andpassword: docker.

Middleware

Here I place any custom middleware the app is using. The custom middleware we're using is based on thekoa-jwt library - but I had to tweak it because it mysteriously didn't report an expired token correctly. Strange, as I thought that would be an important requirement. No biggie.

Models

Our models folder contains two model files - one for users and one for notes. These models are where the actual database calls are made. This keeps things nice and neat - also make actions reusable for the future.

Routes

Very simple - here are our routes. I've broken it down into a few files - this keeps things in control. Each route is nice and thin - all it's doing is calling a controller. Some routes are using that jwt middleware I mentioned earlier. Koa make it really nice and easy to add middleware to a route. Very cool.

Static

Static files - just used for the favicon.

index.js

index.js isn't a folder - it's the brain of the app. Here you'll see we are attaching a bunch of middleware to ourKoa instance. Very slick and straight-forward initialization.

Testing

This project usesJest for testing. Bascially, each API endpoint is tested with working request data to confirm the server behaves correctly when spoken to. Each time the tests are run the migrations get kicked into gear. After the tests are complete the testing database rolls-back - ready for the next test.

TypeScript

So, I added some basic TypeScript support because I've been really digging TypeScript lately. The implementation in this project is not perfect, but it's initialized and a good amount of the files are now converted. I'll get to the rest of the files as soon as I can, but the good news is that any new files needed going forward will be all set to write in TypeScript.

Hit Me Up

Go ahead and fork the project! Message me here if you have questions or submit an issue if needed. I'll be making touch-ups as time goes on. Have fun with this!

License

Copyright 2017 John Datserakis

MIT

About

🤓 This is a simple SPA built using Koa as the backend, Vue as the first frontend, and React as the second frontend. Features MySQL integration, user authentication, CRUD note actions, and async/await.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp