resolver-mongo.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const mongoose = require('mongoose');
  2. const helper = require('./helper');
  3. const Schema = mongoose.Schema,
  4. ObjectId = Schema.ObjectId;
  5. const WorldSchema = new mongoose.Schema({
  6. id: Number,
  7. randomNumber: Number
  8. }, {
  9. collection: 'world'
  10. }),
  11. World = mongoose.model('world', WorldSchema);
  12. const FortuneSchema = new mongoose.Schema({
  13. id: Number,
  14. message: String
  15. }, {
  16. collection: 'fortune'
  17. }),
  18. Fortune = mongoose.model('fortune', FortuneSchema);
  19. // Methods
  20. async function arrayOfRandomWorlds(totalWorldToReturn) {
  21. var totalIterations = helper.sanititizeTotal(totalWorldToReturn);
  22. var arr = [];
  23. return new Promise(async (resolve, reject) => {
  24. for(var i = 0; i < totalIterations; i++) {
  25. arr.push(await World.findOne({ id: helper.randomizeNum() }));
  26. }
  27. if(arr.length == totalIterations) {
  28. resolve(arr);
  29. }
  30. });
  31. };
  32. async function updateRandomWorlds(totalToUpdate) {
  33. const totalIterations = helper.sanititizeTotal(totalToUpdate);
  34. var arr = [];
  35. return new Promise(async (resolve, reject) => {
  36. for(var i = 0; i < totalIterations; i++) {
  37. arr.push(await World.findOneAndUpdate({ id: helper.randomizeNum() }, { randomNumber: helper.randomizeNum() }));
  38. }
  39. if(arr.length == totalIterations) {
  40. resolve(arr);
  41. }
  42. });
  43. };
  44. const sayHello = () => {
  45. var helloWorld = new Object;
  46. helloWorld.message = "Hello, World!";
  47. return JSON.stringify(helloWorld);
  48. };
  49. module.exports = {
  50. Query: {
  51. helloWorld: () => sayHello(),
  52. getAllWorlds: async() => await World.find({}),
  53. singleDatabaseQuery: async() => await World.findOne({ id: helper.randomizeNum() }),
  54. multipleDatabaseQueries: async(parent, args) => await arrayOfRandomWorlds(args.total),
  55. getWorldById: async(parent, args) => await World.findById(args.id),
  56. getAllFortunes: async() => await Fortune.find({}),
  57. getRandomAndUpdate: async(parent, args) => await updateRandomWorlds(args.total)
  58. },
  59. Mutation: {
  60. createWorld: async(parent, args) => {
  61. let randInt = Math.floor(Math.random() * 1000) + 1;
  62. return await World.create({ id: null, randomNumber: randInt });
  63. },
  64. updateWorld: async(parent, args) => {
  65. return await World.update({id: args.id, randomNumber: args.randomNumber});
  66. }
  67. }
  68. }