Implementation of a generic backend of eshop in Crystal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.5 KiB

  1. require "kemal"
  2. require "../*"
  3. require "io"
  4. require "file"
  5. require "math"
  6. require "exception"
  7. require "crypto/bcrypt/password"
  8. require "dir"
  9. require "uuid"
  10. require "uuid/json"
  11. require "kemal/param_parser"
  12. require "../../config"
  13. get "/products" do |context|
  14. ret = Array(Product).new
  15. path = Dir.new(Statics.data_path+"products")
  16. sent = 0
  17. skipped = 0
  18. skip, limit = Statics.extract_skip_info context
  19. path.each do |filename|
  20. if(sent<limit)
  21. begin
  22. if filename.char_at(0)!='.'
  23. if(skipped<skip)
  24. skipped+=1
  25. else
  26. ret.push Product.from_json File.read Statics.data_path+"products/"+filename
  27. sent+=1;
  28. end
  29. end
  30. rescue exception
  31. end
  32. end
  33. end
  34. ret.to_json
  35. end
  36. get "/products/:id" do |context|
  37. begin
  38. ret = Product.from_json File.read Statics.data_path+"products/"+context.params.url["id"]
  39. rescue ex
  40. halt context, status_code: 404, response: ex.to_s
  41. end
  42. ret.to_json
  43. end
  44. post "/products" do |context|
  45. user : User
  46. begin
  47. user = authenticate_admin!(context.request.headers["user"],UUID.new(context.request.headers["api_token"]))
  48. rescue ex
  49. halt context, status_code: 403, response: ex.to_s
  50. end
  51. product = Product.from_json(context.request.body.not_nil!).not_nil!
  52. File.write Statics.data_path+"products/"+product.id.to_s,product.to_json
  53. "OK".to_json
  54. end