index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. const ObjectID = require("mongodb").ObjectID;
  2. const jwt = require('jsonwebtoken')
  3. const jwtSecret = 'CbymrfGfnB'
  4. const anonResolvers = ['login', 'createUser'];
  5. ;(async () => {
  6. const {Savable, slice, getModels} = await require('./models.js')()
  7. class User extends Savable {
  8. static get relations(){
  9. return {
  10. }
  11. }
  12. }
  13. Savable.addClass(User)
  14. const express = require('express');
  15. const express_graphql = require('express-graphql');
  16. const { buildSchema } = require('graphql');
  17. const schema = buildSchema(`
  18. type Query {
  19. login(login: String!, password: String!): String
  20. categories: [Category]
  21. category(_id: ID!): Category
  22. goods: [Good]
  23. good(_id: ID!): Good
  24. myOrders: [Order]
  25. orders: [Order]
  26. }
  27. type Mutation {
  28. createUser(login: String!, password: String!): User
  29. changePassword(password: String!): User
  30. setCategory(cat: CategoryInput!):Category
  31. setGood(good: GoodInput!):Good
  32. setOrder(order: OrderInput):Order
  33. setOrderGood(orderGood: OrderGoodInput):OrderGood
  34. }
  35. type User {
  36. _id: String
  37. login: String
  38. nick : String
  39. orders: [Order]
  40. }
  41. type Category {
  42. _id: ID,
  43. name: String!,
  44. goods: [Good]
  45. }
  46. type Good {
  47. _id: ID,
  48. name: String!,
  49. description: String
  50. price: Float
  51. orderGoods: [OrderGood]
  52. categories: [Category]
  53. }
  54. type OrderGood {
  55. _id: ID,
  56. price: Float,
  57. count: Float,
  58. good: Good,
  59. order: Order
  60. }
  61. type Order {
  62. _id: ID
  63. orderGoods: [OrderGood]
  64. }
  65. input UserInput {
  66. _id: String
  67. login: String
  68. nick : String
  69. }
  70. input CategoryInput {
  71. _id: ID,
  72. name: String!,
  73. goods: [ID]
  74. }
  75. input GoodInput {
  76. _id: ID,
  77. name: String!,
  78. description: String
  79. price: Float
  80. categories: [ID]
  81. }
  82. input OrderGoodInput {
  83. _id: ID,
  84. count: Int!,
  85. good: ID!,
  86. order: ID!
  87. }
  88. input OrderInput {
  89. _id: ID
  90. orderGoods: [ID]
  91. }
  92. `);
  93. var app = express();
  94. app.use(express.static('public'));
  95. const rootResolvers = {
  96. createUser:async function ({login, password}){
  97. let user = await Savable.m.User.findOne({login, password})
  98. if (user)
  99. return null;
  100. user = await (new User({login, password})).save()
  101. user.___owner = user._id.toString()
  102. user.___permissions = {
  103. read: ["owner", "user"]
  104. }
  105. return await user.save()
  106. },
  107. login: async function({login, password}){
  108. console.log(Savable.classes)
  109. const user = await Savable.m.User.findOne({login, password})
  110. if (!user)
  111. return null;
  112. const token = jwt.sign({ sub: {id: user._id, login}}, jwtSecret); //подписывам токен нашим ключем
  113. return token
  114. },
  115. changePassword:async function ({password}, {jwt: {id}, models: {SlicedSavable, User}} ){
  116. id = new ObjectID(id)
  117. const user = await SlicedSavable.m.User.findOne({_id: id})
  118. if (!user)
  119. return null;
  120. user.password = password;
  121. return await user.save()
  122. },
  123. async setCategory({cat}, {jwt: {id}, models: {SlicedSavable, Category}}){
  124. if ('_id' in cat){
  125. let entity = await SlicedSavable.m.Category.findOne({_id: ObjectID(cat._id)})
  126. console.log(entity)
  127. if (entity){
  128. entity.name = cat.name
  129. if (cat.goods){
  130. entity.goods = []
  131. for (goodId of cat.goods){
  132. let good = await SlicedSavable.m.Good.findOne({_id: ObjectID(goodId)});
  133. good && entity.goods.push(good)
  134. }
  135. }
  136. return await entity.save()
  137. }
  138. }
  139. return await (new Category(cat)).save()
  140. },
  141. async categories({}, {jwt: {id}, models: {SlicedSavable, Category}}){
  142. categories = []
  143. for (let category of SlicedSavable.m.Category.find({})){
  144. try {category = await category} catch (e) { break }
  145. categories.push(category)
  146. }
  147. return categories;
  148. },
  149. async category({_id}, {jwt: {id}, models: {SlicedSavable, Category}}){
  150. return await SlicedSavable.m.Category.findOne({_id: ObjectID(_id)});
  151. },
  152. async setGood({good}, {jwt: {id}, models: {SlicedSavable, Good}}){
  153. if ('_id' in good){
  154. let entity = await SlicedSavable.m.Good.findOne({_id: ObjectID(good._id)})
  155. if (entity){
  156. entity.name = good.name
  157. entity.description = good.description
  158. entity.price = good.price
  159. if (good.categories){
  160. console.log(good.categories)
  161. entity.categories = []
  162. for (catId of good.categories){
  163. let cat = await SlicedSavable.m.Category.findOne({_id: ObjectID(catId)});
  164. cat && entity.categories.push(cat)
  165. }
  166. }
  167. return await entity.save()
  168. }
  169. }
  170. return await (new Good(good)).save()
  171. },
  172. async goods({}, {jwt: {id}, models: {SlicedSavable, Good}}){
  173. goods = []
  174. for (let good of SlicedSavable.m.Good.find({})){
  175. try {good = await good} catch (e) { break }
  176. goods.push(good)
  177. }
  178. return goods;
  179. },
  180. async good({_id}, {jwt: {id}, models: {SlicedSavable, Good}}){
  181. return await SlicedSavable.m.Good.findOne({_id: ObjectID(_id)});
  182. },
  183. async setOrder({order}, {jwt: {id}, models: {SlicedSavable, Order, thisUser}}){
  184. if ('_id' in order){
  185. let entity = await SlicedSavable.m.Order.findOne({_id: ObjectID(good._id)})
  186. if (entity){
  187. //entity.name = good.name
  188. //entity.description = good.description
  189. if (order.orderGoods){
  190. entity.orderGoods = []
  191. for (orderGoodId of entity.orderGoods){
  192. let orderGood = await SlicedSavable.m.OrderGood.findOne({_id: ObjectID(orderGoodId)});
  193. orderGood && entity.orderGoods.push(orderGood)
  194. }
  195. }
  196. entity.user = thisUser
  197. return await entity.save()
  198. }
  199. }
  200. order.user = thisUser
  201. return await (new Order(order)).save()
  202. },
  203. async orders({}, {jwt: {id}, models: {SlicedSavable}}){
  204. orders = []
  205. for (let order of SlicedSavable.m.Order.find({})){
  206. try {order = await order} catch (e) { break }
  207. orders.push(order)
  208. }
  209. return order;
  210. },
  211. async myOrders({}, {jwt: {id}, models: {SlicedSavable}}){
  212. orders = []
  213. for (let order of SlicedSavable.m.Order.find({___owner: id.toString(id)})){
  214. try {order = await order} catch (e) { break }
  215. orders.push(order)
  216. }
  217. return orders;
  218. },
  219. async order({_id}, {jwt: {id}, models: {SlicedSavable, Good}}){
  220. return await SlicedSavable.m.Order.findOne({_id: ObjectID(_id)});
  221. },
  222. async setOrderGood({orderGood}, {jwt: {id}, models: {SlicedSavable, OrderGood, thisUser}}){
  223. console.log(orderGood)
  224. let order = await SlicedSavable.m.Order.findOne({'_id': ObjectID(orderGood.order)})
  225. let good = await SlicedSavable.m.Good.findOne ({'_id': ObjectID(orderGood.good)})
  226. if (order && good){
  227. let entity = await SlicedSavable.m.OrderGood.findOne({'order._id': order._id,
  228. 'good._id': good._id})
  229. if (!entity){
  230. entity = new OrderGood({})
  231. }
  232. entity.price = good.price
  233. entity.count = orderGood.count
  234. entity.order = order
  235. entity.good = good
  236. await entity.save()
  237. console.log(entity)
  238. return entity
  239. }
  240. return null;
  241. },
  242. }
  243. app.use('/graphql', express_graphql(async (req, res, gql) => {
  244. if (!gql.query){
  245. return {
  246. schema: schema,
  247. rootValue: rootResolvers,
  248. graphiql: true,
  249. }
  250. }
  251. const operationMatch = gql.query.match(/\{\s*([a-zA-Z]+)\s*/)
  252. const operationName = operationMatch[1]
  253. const authorization = req.headers.authorization
  254. if (operationName === null || anonResolvers.includes(operationName)){
  255. return {
  256. schema: schema,
  257. rootValue: rootResolvers,
  258. graphiql: true,
  259. }
  260. }
  261. if (authorization && authorization.startsWith('Bearer ')){
  262. console.log('token provided')
  263. const token = authorization.substr("Bearer ".length)
  264. const decoded = jwt.verify(token, jwtSecret)
  265. if (decoded){
  266. console.log('token verified', decoded)
  267. let slicedModels = await getModels(decoded.sub.id)
  268. return {
  269. schema: schema,
  270. rootValue: rootResolvers,
  271. graphiql: true,
  272. context: {jwt: decoded.sub,
  273. models: slicedModels}
  274. }
  275. }
  276. }
  277. }))
  278. app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
  279. })()