@fontoxml/fontoxml-development-tools
Version:
Development tools for Fonto.
94 lines (84 loc) • 2.5 kB
JavaScript
import ProfileResult from './ProfileResult.js';
import ProfileResultStatus from './ProfileResultStatus.js';
const DATABASE_FILE_NAME = 'profiles-database.json';
export default class ProfileRepository {
async _getDatabase(cms, currentSession) {
let fileLock;
try {
fileLock = await cms.acquireLock(DATABASE_FILE_NAME);
const json = await cms.getFileWithoutHistory(
DATABASE_FILE_NAME,
currentSession.editSessionToken,
fileLock,
);
if (json === null) {
return {
profiles: [],
};
}
const profilesDatabase = JSON.parse(json);
return profilesDatabase;
} finally {
fileLock?.release();
}
}
/**
* Helper function to find a given profile in a given database. It will look
* up the profile based in its ID.
*
* @param {Object} database The database in which to look for the profile.
* @param {string} profileId The profile id to look for.
*
* @return {Profile} The found profile.
*/
_findProfileInDatabase(database, profileId) {
return database.profiles.find((profile) => profile.profileId === profileId);
}
/**
* Get the profile result obtained from the database.
*
* @param {Object} database
* @param {string} profileId
*
* @return {ProfileResult[]}
*/
_getProfileResult(database, profileId) {
const profileInDatabase = this._findProfileInDatabase(database, profileId);
if (!profileInDatabase) {
return new ProfileResult(ProfileResultStatus.NOT_FOUND, profileId, null);
}
return new ProfileResult(
ProfileResultStatus.OK,
profileId,
profileInDatabase,
);
}
/**
* Returns the profiles identified by the given profiles IDs from the database.
*
* @param {DevelopmentCms} cms
* @param {object} currentSession
* @param {string[]} profileIds
*
* @return {Promise<ProfileResult[]>}
*/
async getProfiles(cms, currentSession, profileIds) {
const database = await this._getDatabase(cms, currentSession);
return profileIds.map((profileId) =>
this._getProfileResult(database, profileId),
);
}
/**
* Returns the profile identified by the given profile IDs from the database.
*
* @param {DevelopmentCms} cms
* @param {object} currentSession
* @param {string[]} profileIds
*
* @return {Promise<ProfileResult>}
*/
async getProfile(cms, currentSession, profileId) {
const database = await this._getDatabase(cms, currentSession);
return this._getProfileResult(database, profileId);
}
}