index.js 10 KB

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