@fontoxml/fontoxml-development-tools
Version:
Development tools for Fonto.
115 lines (104 loc) • 2.74 kB
JavaScript
import ProfileResult from './ProfileResult.js';
import ProfileResultStatus from './ProfileResultStatus.js';
const DATABASE_FILE_NAME = 'profiles-database.json';
export default class ProfileDatabase {
_getDatabase(cms, currentSession) {
if (
!cms.existsSync(DATABASE_FILE_NAME, currentSession.editSessionToken)
) {
return Promise.resolve({
profiles: [],
});
}
return new Promise((resolve, reject) => {
cms.load(
DATABASE_FILE_NAME,
currentSession.editSessionToken,
(error, json) => {
if (error) {
reject(error);
return;
}
try {
const profilesDatabase = JSON.parse(json);
resolve(profilesDatabase);
} catch (error) {
reject(error);
}
},
);
});
}
/**
* 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 {ProfileDatabase} database
* @param {string} profileId
*
* @return {Promise<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[]>}
*/
getProfiles(cms, currentSession, profileIds) {
const databasePromise = this._getDatabase(cms, currentSession);
return databasePromise.then((database) =>
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>}
*/
getProfile(cms, currentSession, profileId) {
const databasePromise = this._getDatabase(cms, currentSession);
return databasePromise.then((database) =>
this._getProfileResult(database, profileId)
);
}
}