All files / resources/api/v2 files.ts

0% Statements 0/141
0% Branches 0/1
0% Functions 0/1
0% Lines 0/141

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175                                                                                                                                                                                                                                                                                                                                                             
import {
  LambdaApiFunction,
  handleResourceApi
} from './_base';
import {
  DocumentQueryConfig,
  mergeDynamoQueriesDocClient
} from './_utils';
 
import { generateApi400Body } from '@/types/api/_shared';
import {
  FullFileObject, GetAllFilesApi, getAllFilesApiQueryValidator
} from '@/types/api/files';
import { TypedQueryInput } from '@/types/backend/dynamo';
import {
  TABLE_DEVICES, TABLE_FILE
} from '@/utils/backend/dynamoTyped';
import { validateObject } from '@/utils/backend/validation';
import { getLogger } from '@/utils/common/logger';
 
const logger = getLogger('files');
 
const defaultListLimit = 100;
const afterAddedIndexNames: {
  [key: string]: undefined | string;
} = {
  StartTimeEmergIndex: 'AddedIndex',
  StartTimeTgIndex: undefined,
  ToneIndex: undefined,
};
 
const GET: LambdaApiFunction<GetAllFilesApi> = async function (event) {
  logger.debug('GET', ...arguments);
 
  const [
    query,
    queryErrors,
  ] = validateObject<GetAllFilesApi['query']>(
    event.multiValueQueryStringParameters || {},
    getAllFilesApiQueryValidator,
    true
  );
  if (
    query === null ||
    queryErrors.length > 0
  ) {
    return [
      400,
      generateApi400Body(queryErrors),
    ];
  }
 
  const baseQueryConfig: TypedQueryInput<FullFileObject> = {
    ScanIndexForward: false,
    TableName: TABLE_FILE,
    Limit: defaultListLimit,
  };
  const queryConfigs: DocumentQueryConfig<FullFileObject>[] = [];
 
  // Generate the base configs using an index. This can be a talkgroup index or emergency index
  if (typeof query.tg !== 'undefined') {
    baseQueryConfig.ExpressionAttributeNames = {
      '#talkgroup': 'Talkgroup',
    };
    baseQueryConfig.IndexName = 'StartTimeTgIndex';
    baseQueryConfig.KeyConditionExpression = '#talkgroup = :talkgroup';
    query.tg
      .forEach(tg => queryConfigs.push({
        ExpressionAttributeValues: {
          ':talkgroup': Number(tg),
        },
      }));
  } else if (typeof query.tone !== 'undefined') {
    baseQueryConfig.ExpressionAttributeNames = {
      '#ToneIndex': 'ToneIndex',
    };
    baseQueryConfig.IndexName = 'ToneIndex';
    baseQueryConfig.KeyConditionExpression = '#ToneIndex = :ToneIndex';
    queryConfigs.push({
      ExpressionAttributeValues: {
        ':ToneIndex': query.tone,
      },
    });
  } else if (typeof query.radioId !== 'undefined') {
    baseQueryConfig.TableName = TABLE_DEVICES;
    baseQueryConfig.ExpressionAttributeNames = {
      '#RadioID': 'RadioID',
    };
    baseQueryConfig.KeyConditionExpression = '#RadioID = :RadioID';
    queryConfigs.push({
      ExpressionAttributeValues: {
        ':RadioID': query.radioId,
      },
    });
  } else {
    let emergencyValues = [
      0,
      1,
    ];
    if (typeof query.emerg !== 'undefined') {
      emergencyValues = query.emerg === 'y'
        ? [ 1, ]
        : [ 0, ];
    }
 
    baseQueryConfig.ExpressionAttributeNames = {
      '#emerg': 'Emergency',
    };
    baseQueryConfig.IndexName = 'StartTimeEmergIndex';
    baseQueryConfig.KeyConditionExpression = '#emerg = :emerg';
    emergencyValues.forEach(emerg => queryConfigs.push({
      ExpressionAttributeValues: {
        ':emerg': emerg,
      },
    }));
  }
 
  if (typeof query.before !== 'undefined') {
    // Add a filter for files recorded before a certain time
    baseQueryConfig.ExpressionAttributeNames['#st'] = 'StartTime';
    baseQueryConfig.KeyConditionExpression += ' AND #st < :st';
 
    queryConfigs.forEach(queryConfig => {
      queryConfig.ExpressionAttributeValues[':st'] = query.before;
    });
  } else if (typeof query.after !== 'undefined') {
    // Add a filter for files recorded after a certain time
    baseQueryConfig.ScanIndexForward = true;
    baseQueryConfig.ExpressionAttributeNames['#st'] = 'StartTime';
    baseQueryConfig.KeyConditionExpression += ' AND #st > :st';
 
    queryConfigs.forEach(queryConfig => {
      queryConfig.ExpressionAttributeValues[':st'] = query.after;
    });
  } else if (typeof query.afterAdded !== 'undefined') {
    // Add a filter for files ADDED after a certain time
    baseQueryConfig.ScanIndexForward = true;
    baseQueryConfig.ExpressionAttributeNames['#added'] = 'Added';
    baseQueryConfig.KeyConditionExpression += ' AND #added > :added';
 
    const newIndex = afterAddedIndexNames[baseQueryConfig.IndexName || ''];
    if (typeof newIndex === 'undefined') {
      delete baseQueryConfig.IndexName;
    } else {
      baseQueryConfig.IndexName = newIndex;
    }
 
    queryConfigs.forEach(queryConfig => {
      queryConfig.ExpressionAttributeValues[':added'] = query.afterAdded;
    });
  }
 
  // Fetch the data
  const data = await mergeDynamoQueriesDocClient<FullFileObject>(
    baseQueryConfig,
    queryConfigs,
    'StartTime',
    'Added'
  );
 
  return [
    200,
    {
      before: data.MinSortKey,
      after: data.MaxSortKey,
      afterAdded: data.MaxAfterKey,
      files: data.Items,
    },
  ];
};
 
export const main = handleResourceApi.bind(null, {
  GET,
});