Git Product home page Git Product logo

johndatserakis / koa-vue-notes-api Goto Github PK

View Code? Open in Web Editor NEW
364.0 20.0 67.0 5.68 MB

🤓 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.

Home Page: https://koa-vue-notes-web.innermonkdesign.com/

License: MIT License

JavaScript 66.22% HTML 9.23% Dockerfile 1.06% Shell 1.05% TypeScript 22.44%
koa node spa backend mysql boilerplate demo template jwt pm2 database api

koa-vue-notes-api's Introduction

   

License Tweet

Koa-Vue-Notes-Api

This is a simple SPA built using Koa as the backend, Vue as the first frontend, and React 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 dependencies
npm i

# Serve using nodemon with hot reload
npm run watch

# Build for production
npm run build

# Lint the project with eslint
npm run lint

# Run tests
npm run test

## 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 latest
NODE_ENV=development knex migrate:latest

# Rollback
NODE_ENV=development knex migrate:rollback

# Run all seeds
NODE_ENV=development knex seed:run

# Make migration
knex migrate:make create_users_table

# Make seed
knex 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 follow this guide. After installing and running redis, you should be able to enter redis-cli ping into a terminal and get PONG 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 using JWT.

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 mainly PHP 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 with Vue and React - I've used mainly jQuery in the past - albeit with the really structured Revealing-Module-Pattern - and using Vue and React 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. For JWT_ACCESS_TOKEN_EXP you can set it to 5m, 5w, 5d etc - although 5m is what I'm using at the moment. Note - we don't set the NODE_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 the JWT_SECRET variable - something random around 32 characters.

This project only responds and listens in JSON. Keep that in mind when send requests through Insomnia 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 and accessToken and a refreshToken back
  • We take the accessToken and decode it using jwt-decode. This gets us the logged in user's information. We stick this in the Vuex/Redux user store. Then we store the refreshToken and accessToken in the user's localStorage.
  • Each protected endpoint will be expecting you to attach the accessToken you have to the call (using Authentication: Bearer)
  • After a short amount of time, the server will respond with 401 TOKEN EXPIRED. When you see this - that means you need to send your refreshToken and user.email to the endpoint that deals with accessToken refreshing.
  • Once you do that, you'll received a brand new accessToken and refreshToken
  • Repeat the process as needed

The src 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 a model to make database calls. There are two controller files present - one for user signup/login/forgot... and one for notes. Note: the UserActionController.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 why UserActionController.js in written in a more procedural way.

DB

Here is our database setup. This project uses Knex to manage migrations and execute queries. I initially wrote wrote all the MySQL calls using raw SQL, but the need for a migrations manager pushed me towards an ORM for the MySQL 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 and koa_vue_notes_testing. In your production environment you would just have koa_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. The knexfile.js used here dynamically attaches to the proper database based the NODE_ENV.

The knexfile.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'll npm i, then create a koa_vue_notes_development database and a koa_vue_notes_testing database, then knex migrate:latest and knex 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, run docker-compose up -d --build to bring up the machine. To stop the machine, run docker-compose down. The main reason docker is used in this case is to host the MySQL database. Make a database named koa-vue-notes_development. Connect through Sequel Pro using host: 127.0.0.1, port: 3360, user: root, and password: docker.

Middleware

Here I place any custom middleware the app is using. The custom middleware we're using is based on the koa-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 our Koa instance. Very slick and straight-forward initialization.

Testing

This project uses Jest 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

koa-vue-notes-api's People

Contributors

johndatserakis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-vue-notes-api's Issues

using docker-compose to run the program but can't get access to the localhost:4000 port

hi , I'm new to koa. After running docker-compose up -d --build under the koa-vue-notes-api-develop directory,the console's output is:
屏幕截图 2023-10-13 142126

However,after running the front-end part, when I tried to login:

屏幕截图 2023-10-13 153607

May be I didn't correctly understand the readme file ?

I don't know what happeded. So I gave up using docker,but try to just using npm to start the backend, however:

屏幕截图 2023-10-13 152550

I think it might be caused by the different version of nodejs?

I would be greatful if you can help me

need help

so i am a windows 10 user, and i really new to use docker, and i use sqlyog for sequel pro replacement, so i had this problem ,
[nodemon] 1.17.5
[0] [nodemon] to restart at any time, enter rs
[0] [nodemon] watching: .
[0] [nodemon] starting node app.js
[0] [nodemon] restarting due to changes...
[0] [nodemon] starting node app.js
[1] > Starting dev server...
[0] Server running at 4000
[0] Running in development v2.0.0
[0] [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
[0] at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
[0] [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
[0] at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
[0] [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379

i know that related with docker, but i dont understand to use it, can you help me?
anyway i miss it too: "development environment, koa_vue_notes_development and koa_vue_notes_testing. In your production environment you would just have koa_vue_notes_production"
that s your read.me text about db, im dont understand what must i made and where , sorry for my bad programming skill . can you help me?

ie 11 error

Hi. How can fix the problem with ie11, from windows 7?
i have this string error "SCRIPT5022: [vuex] vuex requires a Promise polyfill in this browser."

Trouble running on windows

Hi John,

I'm having some trouble running under Windows (10).

Initially, I had trouble getting NODE_ENV set, but I fixed that in package.json by adding 'set' in front of the NODE_ENV directive. Interestingly, i tried using 'cross-env', but it didn't work. Weird.

Now I'm trying to do 'npm run watch', but getting the following:

[email protected] watch C:\xampp\htdocs\koa-notes-api
set NODE_ENV=development & nodemon app.js --exec

[nodemon] 1.12.0
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app.js

C:\xampp\htdocs\koa-notes-api\src\index.js:3
import Koa from 'koa'
^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    ....
    at Object.<anonymous> (C:\xampp\htdocs\koa-notes-api\app.js:12:13)

I'm running node 8.x, so it shouldn't be an ES2015 thing surely? I know this is not really your problem, but do you perhaps have any ideas I can try?

Token in User

Hi. First thanks for sharing your work.Its been a great inspiration for learning koa and vue.

I don't really get what this token in the user model/controller is doing? Maybe I missed something but it seems that it is genreated but not used.

//Now let's generate a token for this user
request.token = await this.generateUniqueToken()

[Q] docker-compose - what are apache & php containers for?

Hi, first off thanks for the amazing example program.

My question is pretty much as in the title - this is our backend service, what are those services declared in docker-compose for?

I'm especially curious about why php image is included.

p2 supports hot reload

Hi John, nice work you have here, I am just looking the same stuff and what you have done is very helpful, thank you. You should check that pm2 supports hot reload with watch, so there is no need to use noDaemon I think. I can send you an example.

Issue Running on Windows 10

Trying to run this on windows 10, changed the watch in package.json to

"watch": "SET NODE_ENV=development & nodemon app.js --exec",

This looks like it works but then I get an error.

`

SET NODE_ENV=development & nodemon app.js --exec

[nodemon] 1.17.5
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app.js
\api\src\index.js:3
import Koa from 'koa'
^^^

SyntaxError: Unexpected identifier
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
[nodemon] app crashed - waiting for file changes before starting...
`

I dont know if its recognizing the import statement, im on latest version of Node.
What do I need to do to get this to run?

Thanks

Question

First of all Thank You for sharing this repo, this is the most complete koa stater I could find.
Can I skip redis setup until deployment ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.