- Sample of GraphQL-Yoga + Express + JWT
- Install mysql server
- Intall
mysqlvia HomeBrew
$ brew install mysql
- Start
mysqlservice as daemon
$ brew services start mysql
- Set root password of mysql database
$ mysql -uroot
mysql> USE mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'qwer1234';
mysql> FLUSH PRIVILEGES;
mysql> quit
- Create
sample_db_graphqldatabase
$ mysql -uroot -p
mysql> CREATE DATABASE sample_db_graphql;
mysql> quit
- Restore mysql from
seeders/dump-sample_db_graphql.sqlfile.
$ mysql -uroot -p sample_db_graphql < ./seeders/dump-sample_db_graphql.sql
- npm install
$ npm install
- If
sh: nodemon: command not founderror occurred$ npm i -g nodemon
- npm start
$ npm start
- Then you've met following messages:
[nodemon] 2.0.7 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `babel-node index.js` Graphql Server Running on localhost:4000You can stop service with
Ctrl-C.
-
Paste and go following URL, http://localhost:4000/play in your favorite web browser (Google Chrome recommended)
-
Type query like followings:
query { getUserInfo(id: "neoroman") { id name } }
-
Meet first error like followings:
... Error: Cannot return null for non-nullable field Query.getUserInfo. ...Now you need models between GraphQL resolvers and MySQL.
-
Install
sequelize-autoif you've not installed$ brew sequelize-auto -
Running
sequelize-autofor generatingGraphQL Schemawith MySQL datebaserootpassword =qwer1234.Warning: using a password on the command line interface can be insecure.
$ sequelize-auto -c config/sequelize-auto.config.json -x qwer1234Now you could find
{TABLE_NAME}.jsfiles in folder./models! -
Open
graphql/resolvers.js- Change codes commente No.1 and No.2 like followings:
const resolvers = { Query: { getUserInfo: async (parent, args, context, info) => { try { // 1 let userId = { id: args.id } const items = await AdminUser.findAll({ where: userId }); return items; } catch(err) {console.log(err);} } }, Mutation: { putUserInfo: async (parent, args, context, info) => { try { // 2 const user = await AdminUser.findOne({ where: { id: args.id } }); if (user) { if (args.password) { user.set('password', args.password); user.set('updateTime', (new Date())); } if (args.email) { user.set('email', args.email); } return await user.save(); } return new Error("putUserInfo: cannot find user:", args.id); } catch(err) { console.log(err) return new Error("putUserInfo", err); }; } } }
- Query to
AdminUsertable where userId == args.id - Update
AdminUsertable where userId == args.id
- Query to
- Change codes commente No.1 and No.2 like followings:
-
Click
playbutton again, you could see the success result, Violla!
