shopify-mysql-session-storage
Version:
mysql custom storage for customer information(Shopify).
118 lines (105 loc) • 3.39 kB
JavaScript
;
const mysql = require('mysql2/promise');
const { Session } = require('@shopify/shopify-api');
const defaultMySQLSessionStorageOptions = {
sessionTableName: 'shopify_sessions'
};
class MySQLSessionStorage {
constructor(dbUrl, opts = {}) {
this.dbUrl = dbUrl;
if (typeof this.dbUrl === 'string') {
this.dbUrl = new URL(this.dbUrl);
}
this.options = Object.assign(
Object.assign({}, defaultMySQLSessionStorageOptions),
opts
);
this.ready = this.init();
}
async storeSession(session) {
await this.ready;
// Note milliseconds to seconds conversion for `expires` property
const entries = session
.toPropertyArray()
.map(([key, value]) =>
key === 'expires'
? [key, Math.floor(value / 1000)]
: [key, value]
);
const query = `
REPLACE INTO ${this.options.sessionTableName}
(${entries.map(([key]) => key).join(', ')})
VALUES (${entries.map(() => `?`).join(', ')})
`;
await this.query(
query,
entries.map(([_key, value]) => value)
);
return true;
}
async loadSession(id) {
await this.ready;
const query = `
SELECT * FROM \`${this.options.sessionTableName}\`
WHERE id = ?;
`;
const [rows] = await this.query(query, [id]);
if (
!Array.isArray(rows) ||
(rows === null || rows === void 0 ? void 0 : rows.length) !== 1
)
return undefined;
const rawResult = rows[0];
return this.databaseRowToSession(rawResult);
}
async deleteSession(id) {
await this.ready;
const query = `
DELETE FROM ${this.options.sessionTableName}
WHERE id = ?;
`;
await this.query(query, [id]);
return true;
}
async deleteSessions(ids) {
await this.ready;
const query = `
DELETE FROM ${this.options.sessionTableName}
WHERE id IN (${ids.map(() => '?').join(',')});
`;
await this.query(query, ids);
return true;
}
async findSessionsByShop(shop) {
await this.ready;
const query = `
SELECT * FROM ${this.options.sessionTableName}
WHERE shop = ?;
`;
const [rows] = await this.query(query, [shop]);
if (
!Array.isArray(rows) ||
(rows === null || rows === void 0 ? void 0 : rows.length) === 0
)
return [];
const results = rows.map((row) => {
return this.databaseRowToSession(row);
});
return results;
}
async disconnect() {
await this.connection.end();
}
async init() {
this.connection = await mysql.createConnection(this.dbUrl.toString());
}
query(sql, params = []) {
return this.connection.query(sql, params);
}
databaseRowToSession(row) {
// convert seconds to milliseconds prior to creating Session object
if (row.expires) row.expires *= 1000;
return Session.fromPropertyArray(Object.entries(row));
}
}
exports.MySQLSessionStorage = MySQLSessionStorage;