saveDoc<T extends FrappeDocument> method

  1. @override
Future<RequestResponse<T?>> saveDoc<T extends FrappeDocument>(
  1. T doc
)
override

Returns the saved document T after saving in the backend and locally.

If a new doc is to be saved, isLocal of the document should be set to true.

If a new doc is saved with the same name, a failure is returned.

Implementation

@override
Future<RequestResponse<T?>> saveDoc<T extends FrappeDocument>(T doc) async {
  await getFrappe()
      .checkAppInstalled(features: ['saveDoc'], throwError: false);

  EmptyDoctypeError.verify(doc.doctype);
  EmptyDocNameError.verify(doc.name);

  final isRenovationCoreInstalled =
      getFrappe().getAppsVersion('renovation_core') != null;

  final response = await Request.initiateRequest(
      url: isRenovationCoreInstalled
          ? '${config.hostUrl}/api/method/renovation/doc/${Uri.encodeComponent(doc.doctype!)}/${doc.isLocal! ? "" : '${Uri.encodeComponent(doc.name!)}'}'
          : '${config.hostUrl}/api/resource/${Uri.encodeComponent(doc.doctype!)}${doc.isLocal! ? "" : '/${Uri.encodeComponent(doc.name!)}'}',
      method: doc.isLocal! ? HttpMethod.POST : HttpMethod.PUT,
      contentType: ContentTypeLiterals.APPLICATION_JSON,
      data: isRenovationCoreInstalled
          ? <String, dynamic>{'doc': doc.toJson()}
          : doc.toJson(),
      isFrappeResponse: false);

  if (response.isSuccess) {
    if (response.data != null && response.data!.message is Map) {
      final savedDoc = doc.fromJson<T>(response.data!.message);
      savedDoc.isLocal = false;
      savedDoc.unsaved = false;
      savedDoc.rawResponse = response.data!.message;
      addToLocals(savedDoc);
      return RequestResponse.success(savedDoc,
          rawResponse: response.rawResponse);
    }
  }
  response.isSuccess = false;
  return RequestResponse.fail(handleError(
      'save_doc',
      response.error ??
          ErrorDetail(
              info: Information(
                  data: response.data,
                  rawResponse: response.rawResponse,
                  httpCode: response.httpCode))));
}