Necessitating derived classes to implement methods without making them publicly accessible

I am currently working with the following interface:

import * as Bluebird from "bluebird";
import { Article } from '../../Domain/Article/Article';

export interface ITextParsingService {
    parsedArticle : Article;
    getText(uri : string) : Bluebird<any>;
}

In addition, I have a class that implements this interface:

import * as Bluebird from 'bluebird';
import * as requestPromise from 'request-promise';
import ApplicationConfiguration from '../../../../config/ApplicationConfiguration';
import { ITextParsingService } from '../ITextParsingService';
import { Article } from '../../../Domain/Article/Article';

export class DiffbotTextParsingService implements ITextParsingService {
    public parsedArticle: Article;
    private articleApiEndpoint;

    constructor() {
        this.articleApiEndpoint = "https://api.diffbot.com/v3/article";
    }

    public getText(url: string) : Bluebird<any> {
        return requestPromise(this.articleApiEndpoint, {
            qs : {
                "url" : url,
                "token" : ApplicationConfiguration.Diffbot.developerToken
            },
            headers : {
                'User-Agent' : 'Request-Promise'
            },
            json : true
        }).then((diffbotResponse) => {
            this.mapReponseToArticle(diffbotResponse.objects[0]);
        }).catch((errorMessage) => {
            return errorMessage;
        })
    }

    private mapReponseToArticle(response : any) {
        this.parsedArticle = new Article(response.diffbotUri,
                                         response.title,
                                         response.author,
                                         new URL(response.authorUrl),
                                         response.text,
                                         new URL(response.pageUrl),
                                         new Date(response.date),
                                         response.humanLanguage);
    }
}

I am looking for a way to require all classes that implement ITextParsingService to also include the mapResponseToArticle method, which is responsible for mapping service responses to a common domain object. While I believe this method should not be public, I am unsure how to enforce this requirement in implementing classes. Are there any suggestions for an alternative pattern to achieve this?

Answer №1

ITextParsingService also includes the method mapResponseToArticle, which essentially maps the response of the service to a common domain object. It's debatable whether this should be a public method or not, but enforcing such a requirement from implementing classes can be tricky.

Finding a solution for this dilemma can be challenging.

Any recommendations for an alternate approach?

One suggestion is to follow a common naming convention and name it _mapResponseToArticle. The use of "_" as a prefix is commonly used in JavaScript to indicate internal elements where true private methods are not available yet 🌹 (but they are on the horizon).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor changes in the ID attribute and ng-model using $watchCollection

My goal is to utilize the $watchCollection feature in my directive to monitor two specific elements. The first element is the ng-model. The second element is the id attribute. I have successfully implemented separate watches for each of them. retur ...

Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows: { 'total_count': 6, 'incomplete_results': false, 'items': [ { 'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2', 'repository_url' ...

Fixing a div at the top post scroll - bug on iOS mobile device

I am looking to achieve a similar effect as demonstrated in the example below: https://css-tricks.com/scroll-fix-content/ Essentially, the goal is to have a div become fixed at the top of the page after scrolling to a certain point. Initially, the div wil ...

How can I only replace every second occurrence in a JS string?

Looking for help with JavaScript: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I thought the result would be '', but it's showing 'a a' instead. Can someone explain what I'm missing? To clarify, I want to r ...

I continuously encounter "undefined" when attempting to retrieve collections

Despite my best efforts, I am unable to retrieve the data from the server using the snapshot docs. I have verified that the collection is named "creaciones" in lowercase. There is one document in the collection with existing data. I have double-checked fo ...

Error message: ParseError: Received an unexpected character '<' while running tests using AVA

Initially encountering an issue within the project built on nuxt, I attempted to resolve it by creating a new project using vue-cli and re-installing AVA via npm. However, this did not have any effect on the problem at hand. Upon researching, I came across ...

Creating an if statement that validates whether all variables have non-null values

I am still getting the hang of javascript and working on some coding projects from my textbooks. The current task involves creating an if statement to check if the values of the elements referenced by the names fname, lname, and zip are all not null. Here ...

Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question: const fetchSidebarData = async () => { let da ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...

What is the best way to incorporate new data into localstorage in a React application?

My attempt to implement and add data into local storage has not been successful as it keeps updating the old data instead of adding new ones. Can someone please explain how to store an array of objects entered by a user in local storage using React JS? ...

Ways to extract information from a JSON dataset

[{"id":7,"message":"This is just a sample message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}] Here is my answer. I am attempting to retrieve some data. I have attempted using data.id but it is unsuccessful and gives me undefined ...

Can you specify a data type for ngFor in Angular?

I am currently employing ngFor to iterate over a collection of a specific type [Menu] within Angular 4.x. During this process, I am looping through a collection property of the menu object (menu.items). Unfortunately, my IDE (Eclipse + Angular IDE) is un ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

"Enhabling tablesorter pagination to ensure that buttons always stay in sync with

I am experiencing an issue with the pagination buttons staying at the bottom of my page, even when there are only 2 entries left on the last page. Check out my table here: Is there a way to make the pagination buttons dynamically move to the top based on ...

Tips on creating a personalized memoizeOne function that delivers the accurate data type

I've implemented a function for object memoization: import memoizeOne from 'memoize-one'; type ArrayWithOneObj = [Record<string, unknown>]; const compareObject = ([obj1]: ArrayWithOneObj, [obj2]: ArrayWithOneObj) => obj1 === obj ...

Do not ask for confirmation when reloading the page with onbeforeunload

I am setting up an event listener for the onbeforeunload attribute to show a confirmation message when a user attempts to exit the page. The issue is that I do not want this confirmation message to appear when the user tries to refresh the page. Is there ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...

Making a standard AJAX request using jQuery without including the XHR header

I am looking to make an ajax-type request using the following headers (or something similar): GET example.com/ajaxapi/article/1 HTTP/1.1 Host: localhost Accept: application/hal+json Cache-Control: no-cache The key aspect here is to accomplish this withou ...

Enhancing code readability in vim with custom Javascript syntax highlighting

Is anyone else experiencing issues with VIM's syntax highlighting for Javascript? I have noticed that at times, the highlighting seems to disappear and I have to scroll around to get it adjusted properly. Does anyone know of any workarounds or soluti ...

Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. T ...