Transform JSON into a TypeScript interface with a specialized Date method

Within my Angular 7 project, there is a Post Model defined as follows:

export interface PostModel {
  id: number;
  created: Date;
  published: boolean;
  title: string; 
}

I have implemented an Angular service method aimed at retrieving posts:

public getPosts(): Observable<PostModel[]> {

  return this.httpClient.get<PostModel[]>(url).pipe(

    map((post: PostModel)) => {

      return {
        id: post.id, 
        created: new Date(post.created),
        published: post.published,
        title: post.title
      };

    })

  };

In the process of converting the API response to PostModel, I discovered that the conversion for the created type to Date does not happen automatically in Angular.

Desiring reusability for the mapping code across various sections of my application, I attempted:

map((post: PostModel)) => return mapPostFromJson(post));

Even though I could convert PostModel to a class and implement mapPostFromJson as its method, I am inclined to retain PostModel as an interface.

The challenge lies in creating the mapPostFromJson method. My attempt looked like this:

mapPostFromJson(data: any) : PostModel {

  return map((post: PostModel) => {

    return { 
      id: post.id, 
      created: new Date(post.created),
      published: post.published,
      title: post.title
    };

  });

}

However, this function fails to compile. I am uncertain about how to utilize map outside of the pipe...

Answer №1

It seems there might be some confusion in understanding your question, but would the mapping function mentioned work for you?

mapPostFromJson(data: any): PostModel {
    return { 
        id: data.id, 
        created: new Date(data.created),
        published: data.published,
        title: data.title
    };
}

If not, you could consider a more generic approach using functional principles by defining general functions that can be reused to create your mappers:

// This function takes a structure of functions and applies them to data, returning a result structure
const mapper = functions => json => Object.entries(json)
    .map(([k, val]) => ({ [k]: (functions[k] || (x => x))(val) }))
    .reduce((acc, o) => Object.assign(acc, o), { });

You can then easily create a mapper and apply it to your JSON data:

// Create a mapper that passes all properties
// while transforming 'created' to a date
const mapPostFromJson = mapper({
    created: x => new Date(x)
});

const post = mapPostFromJson(jsonPost);

With this mapper, all JSON properties will be passed through, except the 'created' field which will be transformed into a date.

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

Can you explain the meaning of `images:Array<Object> = [];` in TypeScript?

Recently, I stumbled upon this code snippet in TypeScript images:Array<Object> = []; I'm curious, what exactly does the "<>" notation signify? ...

Issues with Angular routing after upgrading to Angular 4

After making updates in this way, they can be found here To update on Linux/Mac: run the command npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest type ...

Tips for determining the minimum value within an array of objects across multiple keys using a single function

I am currently tasked with the challenge of determining the minimum value from an array of objects that contain multiple keys. My ultimate goal is to identify the minimum value among all keys or specific keys within the objects. For instance var users = ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

Error message possibly undefined when attempting to apply fill gradient to Highcharts area-spline chart

Currently working with angular 12 and utilizing highcharts. I've been attempting to fill the area spline color with a gradient, but have encountered an error in the process. Any suggestions on how to resolve this issue or what step may be causing the ...

Keeping track of the authentication state in AngularFire2 on page reload to verify if the user is logged

I am facing a challenge in my angular4 app that uses angularfire2. I need to determine if a user is logged in when the page loads. Logging in and out works fine, and I have set up a guard on the router to handle unauthorized access. In one example I came ...

The specified column `EventChart.åå` is not found within the existing database

I've been developing a dashboard application using Prisma, Next.js, and supabase. Recently, I encountered an issue when making a GET request. Prisma throws an error mentioning a column EventChart.åå, with a strange alphabet "åå" that I haven&apos ...

Having difficulties generating ngc and tsc AOT ES5 compatible code

I've explored various options before seeking help here. I have an angular2 library that has been AOT compiled using ngc. Currently, I am not using webpack and solely relying on plain npm scripts. Below is the tsconfig file being utilized: { "comp ...

What is the best way to generate an index.ts file in an Angular 14 shared library that exports all contents from a specific directory?

Utilizing Angular 14 for my shared library project, the structure looks like this: + projects + my-lib - package.json + src - public-api.ts + lib + helpers - index.ts ...

Validate the presence of a value in AngularFire and if not found, proceed to create it

I recently started using AngularFire, and since the update to AngularFire5, I've been encountering some issues. My goal is to create a 'room' with a unique id: name pair. When a user inputs a name, I need to check if that name already exists ...

Components within Angular components

Can an Angular component be created to accept the following structure: <app-parent> <app-child>Option 1</app-child> <app-child>Option 2</app-child> </app-parent> This component would then parse and handle this struct ...

Angular - Utilizing nested arrays for efficient file uploading

I am currently working on building a file uploader using Angular. My goal is to be able to upload different types of files, with each button capable of uploading multiple files at once. However, I am running into an issue where the uploaded files are not b ...

There was an error in the CSS syntax in the production environment due to a missed semicolon

Trying to execute the npm build command "webpack --mode=production --config ./config/webpack.config.prod.js" on our project results in an issue. The issue arises when I include the bootstrap file in my tsx file as shown below. import bs from "../../../../ ...

Switching Theme Dynamically in a Multi-tenant Next.js + Tailwind App

I'm currently developing a Next.js + Tailwind application that supports multiple tenants and allows each tenant to easily switch styles or themes. I've been struggling with the idea of how to implement this feature without requiring a rebuild of ...

The map component does not render when the agm-map is placed within the component

Objective I am attempting to encapsulate an <agm-map> within my custom <app-map> component, but it is not appearing in the HTML output. The agm (angular google maps) library is properly configured and the map displays correctly when the <a ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

Is it possible to automatically open the Tinymce Comments sidebar without the need for a manual button click?

After successfully implementing the Tinymce comments plugin into our configuration, we have come across a request from our users. They would like the 'showcomments' button to automatically trigger on page load, displaying the sidebar containing t ...

What causes React component state initialization to return a `never` type when set to null?

Initializing a component's state to null outside of the constructor results in the state having the type never in the render function. However, when the state is initialized within the constructor, the correct type is maintained. Despite many StackO ...

Upon deployment, Angular encounters issues with routing to lazy loaded modules

I recently completed development on a new Angular application that utilizes lazy loading for improved performance. During local testing using ng serve (or ng serve --prod to mimic production mode), the app compiled without errors and functioned properly. ...