saveGame.js 753 B

123456789101112131415161718192021222324252627282930
  1. console.log("Save game");
  2. const throwError = (message, code = 400) => {
  3. const errorObject = new Error(message);
  4. errorObject.statusCode = code;
  5. throw errorObject;
  6. };
  7. const main = async ({ store, id, userId, body }) => {
  8. let existingGame = null;
  9. if (!userId) {
  10. throwError("Game creation not allowed for unauthenticated users", 403);
  11. }
  12. try {
  13. existingGame = await store.get("game", id);
  14. } catch {
  15. console.log("Game not found");
  16. }
  17. if (existingGame && existingGame.owner && existingGame.owner !== userId) {
  18. console.log("Forbidden");
  19. throwError("Modification allowed only for owner", 403);
  20. }
  21. let { owner = userId } = body;
  22. const result = await store.save("game", id, { ...body, owner });
  23. return result;
  24. };