33 lines
2.5 KiB
JavaScript
33 lines
2.5 KiB
JavaScript
const { createRequire } = require('node:module');
|
|
const { readFileSync } = require('node:fs');
|
|
const path = require('node:path');
|
|
const assert = require('node:assert/strict');
|
|
const load = process.env.REFERRAL_TEST_PACKAGE_JSON ? createRequire(process.env.REFERRAL_TEST_PACKAGE_JSON) : require;
|
|
const { PGlite } = load('@electric-sql/pglite');
|
|
(async()=>{
|
|
const db=new PGlite();
|
|
try {
|
|
await db.exec(`CREATE TABLE notifications(id BIGINT PRIMARY KEY,user_id BIGINT,receiver_type TEXT,channel TEXT,is_read BOOLEAN DEFAULT FALSE,created_at TIMESTAMPTZ DEFAULT NOW(),read_at TIMESTAMPTZ);
|
|
INSERT INTO notifications(id,user_id,receiver_type,channel) VALUES (1,42,'user','in_app'),(2,42,'team_member','in_app'),(3,99,'user','in_app');`);
|
|
const source=readFileSync(path.join(__dirname,'../query/notification.sql'),'utf8');
|
|
function sql(name){
|
|
let statement=source.split('-- name: '+name+' :')[1].split('\n').slice(1).join('\n').split('-- name:')[0];
|
|
const positional=[...statement.matchAll(/\$(\d+)/g)].map(match=>Number(match[1]));let next=Math.max(...positional)+1;
|
|
for(const argument of ['receiver_type','requester_id']){if(statement.includes("sqlc.arg('"+argument+"')")){statement=statement.replaceAll("sqlc.arg('"+argument+"')",'$'+next++);}}
|
|
return statement;
|
|
}
|
|
assert.deepEqual((await db.query(sql('GetUserNotifications'),[42,20,0,'user'])).rows.map(row=>row.id),[1]);
|
|
assert.deepEqual((await db.query(sql('GetUserNotifications'),[42,20,0,'team_member'])).rows.map(row=>row.id),[2]);
|
|
assert.equal((await db.query(sql('MarkNotificationAsRead'),[2,'user',42])).rows.length,0,'receiver collision');
|
|
assert.equal((await db.query(sql('MarkNotificationAsRead'),[3,'user',42])).rows.length,0,'other customer');
|
|
await db.query(sql('MarkAllUserNotificationsAsRead'),[42,'user']);
|
|
assert.equal((await db.query('SELECT is_read FROM notifications WHERE id=1')).rows[0].is_read,true);
|
|
assert.equal((await db.query('SELECT is_read FROM notifications WHERE id=2')).rows[0].is_read,false,'staff row unchanged');
|
|
assert.equal(Number((await db.query(sql('CountUnreadNotifications'),[42,'team_member'])).rows[0].count),1);
|
|
assert.equal((await db.query(sql('DeleteUserInAppNotification'),[2,42,'user'])).affectedRows,0);
|
|
await db.query(sql('DeleteUserNotifications'),[42,'user']);
|
|
assert.deepEqual((await db.query('SELECT id FROM notifications ORDER BY id')).rows.map(row=>row.id),[2,3]);
|
|
console.log('Notification SQL audience isolation checks passed.');
|
|
}finally{await db.close()}
|
|
})().catch(error=>{console.error(error);process.exitCode=1});
|