setDataSampleAttachment method

  1. @override
Future<Document?> setDataSampleAttachment(
  1. String dataSampleId,
  2. ByteStream body, {
  3. String? documentName,
  4. String? documentVersion,
  5. String? documentExternalUuid,
  6. String? documentLanguage,
})
override

Add or update the attachment of a DataSample

Link an attachment or update the attachment of a data sample

Parameters:

  • String dataSampleId (required):

  • ByteStream body (required):

  • String documentName:

  • String documentVersion:

  • String documentExternalUuid:

  • String documentLanguage:

Implementation

@override
Future<Document?> setDataSampleAttachment(
  String dataSampleId,
  ByteStream body,
  {String? documentName, String? documentVersion, String? documentExternalUuid, String? documentLanguage}
) async {

  final localCrypto = api.crypto;
  final currentUser = (await api.baseUserApi.getCurrentUser())
      ?? (throw StateError("There is no user currently logged in. You must call this method from an authenticated MedTechApi"));

  final existingDataSample = await getDataSample(dataSampleId);

  final contactDataSample = (await _getContactOfDataSample(localCrypto, currentUser, existingDataSample!)).item2
      ?? throwFormatException("Could not find batch information of the data sample $dataSampleId");

  final patientIdOfContact = (await _getPatientIdOfContact(localCrypto, currentUser, contactDataSample!))
      ?? throwFormatException("Can not set an attachment to a data sample not linked to a patient");

  final documentToCreate = base_api.DecryptedDocumentDto(
      id: uuid.v4(options: {'rng': UuidUtil.cryptoRNG}),
      name: documentName,
      version: documentVersion,
      externalUuid: documentExternalUuid,
      mainUti: UtiDetector.getUtiFor(documentName)
  );


  final documentCC = documentCryptoConfig(localCrypto);
  final createdDocument = await api.baseDocumentApi.createDocument(currentUser, documentToCreate, documentCC) ??
      throwFormatException("Could not create document for data sample $dataSampleId");

  // Update data sample with documentId
  final contentIso = documentLanguage ?? "en";
  existingDataSample.content[contentIso] = Content(documentId: createdDocument!.id);
  createOrModifyDataSampleFor(patientIdOfContact!, existingDataSample);

  // Add attachment to document
  List<int> docDigest = [];
  final String? docEncKey = (await _getDocumentEncryptionKeys(localCrypto, currentUser, createdDocument)).firstOrNull;
  await api.baseDocumentApi.setAttachmentTo(currentUser, createdDocument.id, ByteStream(body.map((bytes) {
    docDigest = bytes;
    return bytes;
  })), docEncKey, documentCC);

  // Update document with digest
  createdDocument.hash = sha256.convert(docDigest).toString();
  final finalDoc = await api.baseDocumentApi.modifyDocument(currentUser, createdDocument, documentCC);

  return finalDoc?.toDocument();
}