Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 1x 1x | 'use strict';
const mssql = require('mssql');
/**
* Cache storage for Facebook attachments
*
* @class
*/
class AttachmentCache {
/**
*
* @param {Promise<mssql.ConnectionPool>} pool
*/
constructor (pool) {
this._pool = pool;
}
/**
*
* @param {string} url
* @returns {Promise<number|null>}
*/
async findAttachmentByUrl (url) {
const cp = await this._pool;
const r = cp.request();
const query = 'SELECT attachmentId FROM attachments WHERE attachments.id=@url';
const { recordset } = await r
.input('url', mssql.VarChar, url)
.query(query);
const [res] = recordset;
return res ? res.attachmentId : null;
}
/**
* @param {string} url
* @param {number} attachmentId
*/
async _simpleUpdate (url, attachmentId) {
const cp = await this._pool;
const r = cp.request();
await r
.input('url', mssql.VarChar, url)
.input('attachmentId', mssql.Int, attachmentId)
.query('UPDATE attachments SET id = @url, attachmentId = @attachmentId WHERE id = @url');
return true;
}
/**
*
* @param {string} url
* @param {number} attachmentId
* @returns {Promise}
*/
async saveAttachmentId (url, attachmentId) {
const cp = await this._pool;
const r = cp.request();
const oldAttachmentId = await this.findAttachmentByUrl(url);
if (!oldAttachmentId) {
try {
await r
.input('url', mssql.VarChar, url)
.input('attachmentId', mssql.Int, attachmentId)
.query('INSERT INTO attachments (id, attachmentId) VALUES (@url, @attachmentId);');
} catch (e) {
// 2627 is unique constraint (includes primary key), 2601 is unique index
if (e.number === 2601 || e.number === 2627) {
return this._simpleUpdate(url, attachmentId);
}
throw e;
}
} else if (attachmentId === oldAttachmentId) {
return true;
} else {
return this._simpleUpdate(url, attachmentId);
}
return true;
}
}
module.exports = AttachmentCache;
|