@saleor/app-sdk
Version:
SDK for building great Saleor Apps
83 lines (81 loc) • 2.51 kB
JavaScript
import {
createAPLDebug
} from "../../chunk-ORQVZRNL.mjs";
import "../../chunk-CPDLIPGD.mjs";
// src/APL/file/file-apl.ts
import { promises as fsPromises } from "fs";
var debug = createAPLDebug("FileAPL");
var FileAPL = class {
constructor(config = {}) {
this.fileName = config?.fileName || ".saleor-app-auth.json";
}
/**
* Load auth data from a file and return it as AuthData format.
* In case of incomplete or invalid data, return `undefined`.
*/
async loadDataFromFile() {
debug(`Will try to load auth data from the ${this.fileName} file`);
let parsedData = {};
try {
parsedData = JSON.parse(await fsPromises.readFile(this.fileName, "utf-8"));
debug("%s read successfully", this.fileName);
} catch (err) {
debug(`Could not read auth data from the ${this.fileName} file`, err);
debug(
"Maybe apl.get() was called before app was registered. Returning empty, fallback data (undefined)"
);
return void 0;
}
const { token, saleorApiUrl, appId, jwks } = parsedData;
if (token && saleorApiUrl && appId) {
debug("Token found, returning values: %s", `${token[0]}***`);
const authData = { token, saleorApiUrl, appId };
if (jwks) {
authData.jwks = jwks;
}
return authData;
}
return void 0;
}
/**
* Save auth data to file.
* When `authData` argument is empty, will overwrite file with empty values.
*/
async saveDataToFile(authData) {
debug(`Trying to save auth data to the ${this.fileName} file`);
const newData = authData ? JSON.stringify(authData) : "{}";
try {
await fsPromises.writeFile(this.fileName, newData);
debug("Successfully written file %", this.fileName);
} catch (err) {
debug(`Could not save auth data to the ${this.fileName} file`, err);
throw new Error("File APL was unable to save auth data");
}
}
async get(saleorApiUrl) {
const authData = await this.loadDataFromFile();
if (saleorApiUrl === authData?.saleorApiUrl) {
return authData;
}
return void 0;
}
async set(authData) {
await this.saveDataToFile(authData);
}
async delete(saleorApiUrl) {
const authData = await this.loadDataFromFile();
if (saleorApiUrl === authData?.saleorApiUrl) {
await this.saveDataToFile();
}
}
async getAll() {
const authData = await this.loadDataFromFile();
if (!authData) {
return [];
}
return [authData];
}
};
export {
FileAPL
};