From af2797f12a1e2a809c05a791c7cfeeb915a039b9 Mon Sep 17 00:00:00 2001 From: keyan Date: Tue, 14 Sep 2021 12:55:59 -0500 Subject: [PATCH] make post boost transactional --- api/resolvers/item.js | 9 +--- .../20210914173926_item_boost/migration.sql | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 7 deletions(-) create mode 100644 prisma/migrations/20210914173926_item_boost/migration.sql diff --git a/api/resolvers/item.js b/api/resolvers/item.js index 753429fb..3bb364c7 100644 --- a/api/resolvers/item.js +++ b/api/resolvers/item.js @@ -421,13 +421,8 @@ const createItem = async (parent, { title, url, text, boost, parentId }, { me, m } const [item] = await serialize(models, - models.$queryRaw(`${SELECT} FROM create_item($1, $2, $3, $4, $5) AS "Item"`, - title, url, text, Number(parentId), Number(me.id))) - - if (boost) { - await serialize(models, - models.$queryRaw`SELECT item_act(${item.id}, ${me.id}, 'BOOST', ${Number(boost)})`) - } + models.$queryRaw(`${SELECT} FROM create_item($1, $2, $3, $4, $5, $6) AS "Item"`, + title, url, text, Number(boost || 0), Number(parentId), Number(me.id))) await createMentions(item, models) diff --git a/prisma/migrations/20210914173926_item_boost/migration.sql b/prisma/migrations/20210914173926_item_boost/migration.sql new file mode 100644 index 00000000..db0490b6 --- /dev/null +++ b/prisma/migrations/20210914173926_item_boost/migration.sql @@ -0,0 +1,49 @@ +-- make sure we nuke the old versions +DROP FUNCTION create_item(text,text,text,integer,integer); + +CREATE OR REPLACE FUNCTION create_item(title TEXT, url TEXT, text TEXT, boost INTEGER, parent_id INTEGER, user_id INTEGER) +RETURNS "Item" +LANGUAGE plpgsql +AS $$ +DECLARE + user_sats INTEGER; + free_posts INTEGER; + free_comments INTEGER; + freebie BOOLEAN; + item "Item"; +BEGIN + PERFORM ASSERT_SERIALIZED(); + + SELECT (msats / 1000), "freePosts", "freeComments" + INTO user_sats, free_posts, free_comments + FROM users WHERE id = user_id; + + freebie := (parent_id IS NULL AND free_posts > 0) OR (parent_id IS NOT NULL AND free_comments > 0); + + IF NOT freebie AND 1 > user_sats THEN + RAISE EXCEPTION 'SN_INSUFFICIENT_FUNDS'; + END IF; + + INSERT INTO "Item" (title, url, text, "userId", "parentId", created_at, updated_at) + VALUES (title, url, text, user_id, parent_id, now_utc(), now_utc()) RETURNING * INTO item; + + IF freebie THEN + IF parent_id IS NULL THEN + UPDATE users SET "freePosts" = "freePosts" - 1 WHERE id = user_id; + ELSE + UPDATE users SET "freeComments" = "freeComments" - 1 WHERE id = user_id; + END IF; + ELSE + UPDATE users SET msats = msats - 1000 WHERE id = user_id; + + INSERT INTO "ItemAct" (sats, "itemId", "userId", act, created_at, updated_at) + VALUES (1, item.id, user_id, 'VOTE', now_utc(), now_utc()); + END IF; + + IF boost > 0 THEN + PERFORM item_act(item.id, user_id, 'BOOST', boost); + END IF; + + RETURN item; +END; +$$; \ No newline at end of file