Apex Cache RecordTypes for fast retrieval

Apex class to lookup record types and cache them

  private static Map<Schema.SObjectType,Map<String,Id>> rtypesCache;

static {
   rtypesCache = new Map<Schema.SObjectType,Map<String,Id>>();//convenient map, formatted from r    esults.
}

  public static Map<String, Id> getRecordTypeMapForObjectGeneric(Schema.SObjectType token) {
      Map<String, Id> mapRecordTypes = rtypesCache.get(token);
      if (mapRecordTypes == null) {
          mapRecordTypes = new Map<String, Id>();
          rtypesCache.put(token,mapRecordTypes);
      } else {
           return mapRecordTypes;
      }

      Schema.DescribeSObjectResult obj = token.getDescribe();
      if (results == null || results.isEmpty()) {
          String soql = 'SELECT Id, Name, DeveloperName, sObjectType FROM RecordType WHERE IsActive = TRUE';
          try {
              results = Database.query(soql);
          } catch (Exception ex) {
              results = new List<SObject>();
          }
      }

      Map<Id,Schema.RecordTypeInfo> recordTypeInfos = obj.getRecordTypeInfosByID();
      for (SObject rt : results) {
          if (recordTypeInfos.get(rt.Id) != null) {
              if (recordTypeInfos.get(rt.Id).isAvailable()) {
                  mapRecordTypes.put(String.valueOf(rt.get('DeveloperName')),rt.Id);
              }
              else {
                  System.debug('The record type ' + rt.get('DeveloperName') + ' for object ' + rt.get('sObjectType') + ' is not availiable for the user.');
              }
          }
      }
      return mapRecordTypes;
    }

Test Class

  @isTest(SeeAllData=true) static void testGetRecordTypeMapForObjectGeneric(){
      Test.startTest();
        Map<String, Id> caseRecordTypeId = App_Service.getRecordTypeMapForObjectGeneric(Case.SobjectType);
        System.Assert(caseRecordTypeId.get('Error')!=null);
        System.Assert(caseRecordTypeId.get('Internal')==null);
      Test.stopTest();
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: