import mongoose from "mongoose" ; import { DimensionInterface } from "../../types/dimension" ; import { getConfigDimensions , usingFileConfig } from "../init/config" ; const dimensionSchema = new mongoose . Schema ( { id : String , organization : { type : String , index : true , } , datasource : String , name : String , sql : String , dateCreated : Date , dateUpdated : Date , } ) ; dimensionSchema . index ( { id : 1 , organization : 1 } , { unique : true } ) ; type DimensionDocument = mongoose . Document & DimensionInterface ; const DimensionModel = mongoose . model < DimensionDocument > ( "Dimension" , dimensionSchema ) ; function toInterface ( doc ) { return doc . toJSON ( ) ; } export async function createDimension ( dimension ) { return toInterface ( await DimensionModel . create ( dimension ) ) ; } export async function findDimensionsByOrganization ( organization ) { if ( usingFileConfig ( ) ) { return getConfigDimensions ( organization ) ; } return ( await DimensionModel . find ( { organization } ) ) . map ( toInterface ) ; } export async function findDimensionById ( id , organization ) { if ( usingFileConfig ( ) ) { return getConfigDimensions ( organization ) . filter ( ( d ) => d . id === id ) [ 0 ] ; } const doc = await DimensionModel . findOne ( { id , organization } ) ; return doc ? toInterface ( doc ) : null ; } export async function findDimensionsByDataSource ( datasource , organization ) { if ( usingFileConfig ( ) ) { return getConfigDimensions ( organization ) . filter ( ( d ) => d . datasource === datasource ) ; } return ( await DimensionModel . find ( { datasource , organization } ) ) . map ( toInterface ) ; } export async function updateDimension ( id , organization , updates ) { if ( usingFileConfig ( ) ) { throw new Error ( "Cannot update. Dimensions are being managed by config.yml" ) ; } await DimensionModel . updateOne ( { id , organization } , { $set : updates } ) ; } export async function deleteDimensionById ( id , organization ) { if ( usingFileConfig ( ) ) { throw new Error ( "Cannot delete. Dimensions are being managed by config.yml" ) ; } await DimensionModel . deleteOne ( { id , organization , } ) ; }