A plugin for Strapi Headless CMS that provides the ability to transform the API request or response.

Overview

strapi-plugin-transformer

A plugin for Strapi that provides the ability to transform the API request and/or response.

Downloads Install size Package version

Requirements

The installation requirements are the same as Strapi itself and can be found in the documentation on the Quick Start page in the Prerequisites info card.

Supported Strapi versions

  • v4.x.x

NOTE: While this plugin may work with the older Strapi versions, they are not supported, it is always recommended to use the latest version of Strapi.

Installation

npm install strapi-plugin-transformer

# OR

yarn add strapi-plugin-transformer

Configuration

The plugin configuration is stored in a config file located at ./config/plugins.js. If this file doesn't exists, you will need to create it.

A sample configuration

module.exports = ({ env }) => ({
  // ..
 'transformer': {
    enabled: true,
    config: {
      prefix: '/api/',
      responseTransforms: {
        removeAttributesKey: true,
        removeDataKey: true,
      }
    }
  },
  // ..
});

IMPORTANT NOTE: Make sure any sensitive data is stored in env files.

The Complete Plugin Configuration Object

Property Description Type Default Required
prefix The prefix for the API String '/api/' No
responseTransforms The transformations to enable for the API response Object undefined No
responseTransforms.removeAttributesKey Removes the attributes key from the response Boolean false No
responseTransforms.removeDataKey Removes the data key from the response Boolean false No

Usage

Once the plugin has been installed, configured and enabled any request to the Strapi API will be auto transformed.

Current Supported Transformations

Remove the attributes key

This response transform will remove the attributes key from the response and shift all of its properties up one level.

Before

{
  "data": {
    "id": 1,
    "attributes": {
      "title": "Lorem Ipsum",
      "createdAt": "2022-02-11T01:51:49.902Z",
      "updatedAt": "2022-02-11T01:51:52.797Z",
      "publishedAt": "2022-02-11T01:51:52.794Z",
      "ipsum": {
        "data": {
          "id": 2,
          "attributes": {
            "title": "Dolor sat",
            "createdAt": "2022-02-15T03:45:32.669Z",
            "updatedAt": "2022-02-17T00:30:02.573Z",
            "publishedAt": "2022-02-17T00:07:49.491Z",
          },
        },
      },
    },
  },
  "meta": {},
}

After

{
  "data": {
    "id": 1,
    "title": "Lorem Ipsum",
    "createdAt": "2022-02-11T01:51:49.902Z",
    "updatedAt": "2022-02-11T01:51:52.797Z",
    "publishedAt": "2022-02-11T01:51:52.794Z",
    "ipsum": {
      "data": {
        "id": 2,
        "title": "Dolor sat",
        "createdAt": "2022-02-15T03:45:32.669Z",
        "updatedAt": "2022-02-17T00:30:02.573Z",
        "publishedAt": "2022-02-17T00:07:49.491Z",
      },
    },
  },
  "meta": {},
}

Remove the data key

This response transform will remove the data key from the response and shift the attribute data to be top level.

Before

{
  "data": {
    "id": 1,
    "attributes": {
      "title": "Lorem Ipsum",
      "createdAt": "2022-02-11T01:51:49.902Z",
      "updatedAt": "2022-02-11T01:51:52.797Z",
      "publishedAt": "2022-02-11T01:51:52.794Z",
      "ipsum": {
        "data": {
          "id":2,
          "attributes": {
            "title": "Dolor sat",
            "createdAt": "2022-02-15T03:45:32.669Z",
            "updatedAt": "2022-02-17T00:30:02.573Z",
            "publishedAt": "2022-02-17T00:07:49.491Z",
          },
        },
      },
    },
  },
  "meta": {},
}

After

{
  "data": {
    "id": 1,
    "attributes": {
      "title": "Lorem Ipsum",
      "createdAt": "2022-02-11T01:51:49.902Z",
      "updatedAt": "2022-02-11T01:51:52.797Z",
      "publishedAt": "2022-02-11T01:51:52.794Z",
      "ipsum": {
        "id":2,
        "attributes": {
          "title": "Dolor sat",
          "createdAt": "2022-02-15T03:45:32.669Z",
          "updatedAt": "2022-02-17T00:30:02.573Z",
          "publishedAt": "2022-02-17T00:07:49.491Z",
        },
      },
    },
  },
  "meta": {},
}

Bugs

If any bugs are found please report them as a Github Issue

Comments
  • struggling with initial setup, data not transforming

    struggling with initial setup, data not transforming

    Hi 👋

    I have been wrestling all day with the new Strapi version. I used v3 and understood what was happening with the JSON response. The new version seems needlessly complicated 😿. I found your plugin on a forum post. I'm not sure if I am missing a step, but my data is not being transformed (as far as I can tell).

    • I installed and added the plugin config as you wrote in the readme. Package.json looks good. Config is in a top-level folder.
    • I also restarted both servers.
    • My console output remains the same. Screen Shot 2022-08-30 at 7 03 48 PM

    In v3 I was able to .map over my response, but with attributes being an object inside of data now, I'm lost.

    If it helps to know, I am receiving the data with a fetch request and using getStaticProps to connect the data to the front-end. The map function is aware there are five items in the array, but can't access anything further.

    Is there something else I need to change? I'm using Strapi and Next.js. I was ecstatic to find this after a long day. I hope I can get it working. Thank you for your help 🙇‍♀️.

    opened by stephhappens 10
  • Transformer not working in v4 strapi

    Transformer not working in v4 strapi

    Hello! Thanks for the plugin!

    I'm trying to use transformer in a strapi v4 app. When calling the endpoint the data is not transformed. I followed the documentation and it still didn't work

    my ./config/plugins.js

    module.exports = ({ env }) => ({
     'transformer': {
        enabled: true,
        config: {
          prefix: '/api/',
          responseTransforms: {
            removeAttributesKey: true,
            removeDataKey: true,
          }
        }
      },
    });
    

    my package.json

        "@strapi/plugin-graphql": "^4.2.0",
        "@strapi/plugin-i18n": "4.2.0",
        "@strapi/plugin-users-permissions": "4.2.0",
        "@strapi/strapi": "4.2.0",
        "pg": "8.6.0",
        "strapi-plugin-ckeditor5": "^2.1.1-rc.1",
        "strapi-plugin-transformer": "^2.0.2"
      
    
    opened by FernandoAme 9
  • Some components do not work in version 4.1.0?

    Some components do not work in version 4.1.0?

    In strapi version 4.0.7, getting response like below

    {
      "data": {
        "id": 1,
        "title": "the title",
        "componentA": {
            "id": 1,
            "content": "Hello!",
        }
        "createdAt": "2022-02-11T01:51:49.902Z",
        "updatedAt": "2022-02-11T01:51:52.797Z",
        "publishedAt": "2022-02-11T01:51:52.794Z",
      },
      "meta": {},
    }
    

    But when I upgrade strapi to version 4.1.0, the response I get is like below

    {
      "data": {
        "id": 1,
        "title": "the title",
        "componentA": {
            "data": {           <--- here
                "id": 1,
                "content": "Hello!",
            }
        }
        "createdAt": "2022-02-11T01:51:49.902Z",
        "updatedAt": "2022-02-11T01:51:52.797Z",
        "publishedAt": "2022-02-11T01:51:52.794Z",
      },
      "meta": {},
    }
    

    Strapi version: 4.1.0 Plugin version: 1.0.3

    opened by be90728 8
  • Not work on strapi v4.5.2

    Not work on strapi v4.5.2

    Not supported in new strapi versions.

    "@strapi/strapi": "4.5.2", "engines": { "node": ">=14.19.1 <=18.x.x", "npm": ">=6.0.0" },

    opened by whydnxx 6
  • Transformer not working when rest-cache is enabled

    Transformer not working when rest-cache is enabled

    Hi

    Thanks for an awesome plugin :-)

    I just wanted to let you know that I have submitted this issue: https://github.com/strapi-community/strapi-plugin-rest-cache/issues/25

    The gist of it is this: "When using strapi-plugin-transformer and rest-cache plugin only the first request from api is transformed. Subsequent and therefore cached api requests are not transformed".

    I'm guessing it mostly has to do with rest-cache plugin not taking transformer in to account, but I don't know.

    opened by orvad 6
  • Feature request: flatten populated data

    Feature request: flatten populated data

    In Strapi v4* (and already using strapi-plugin-transformer) when populating fields, the joined entity comes back flatten as expected :+1:

    However, they have also added a data field, so you get something like:

    {
      image: {
       data: {
          id: 1,
          //...
        }
     }
    }
    

    it would be great if, like with the attributes field, the response is flattened to:

    {
      image: {
          id: 1,
          //...
     }
    }
    

    not sure how complex this would be but just a thought

    enhancement 
    opened by cortopy 6
  • [Feature Request] Option to disable/enable transformation for specific routes or requests

    [Feature Request] Option to disable/enable transformation for specific routes or requests

    Hi,

    this plugin was just presented in the Strapi Community Call and it looks potentially very useful to solve a problem that my team currently faces:

    We're currently migrating from v3 to v4. I understand that v4's API responses are structured significantly different from v3's API responses and it looks like your transformer plugin brings v4's API responses closer to the format that v3 returned. This could potentially simplify the refactoring that is needed in our applications that consume data from Strapi or at least allow us to do it step by step.

    Would it be possible to enable or disable the response transformation executed by your plugin by route (e.g. with a more atomic configuration) or by request (e.g. by providing a certain request header)?

    opened by GregorSondermeier 5
  • Plugin not transforming on Strapi v4.1.12

    Plugin not transforming on Strapi v4.1.12

    Hi,

    I have installed the plugin in my Strapi v4.1.12 and update the plugin.js as mentioned in the docs but the response is not transforming. I have also tried restarting the Strapi.

    My dependencies are as follows:

    ...
     "dependencies": {
        "@strapi/plugin-i18n": "4.1.12",
        "@strapi/plugin-sentry": "^4.1.12",
        "@strapi/plugin-users-permissions": "4.1.12",
        "@strapi/strapi": "4.1.12",
        "pg": "^8.7.3",
        "strapi-plugin-import-export-entries": "^1.2.0",
        "strapi-plugin-transformer": "^2.0.1"
      }
    ...
    

    plugin.js

    module.exports = ({ env }) => ({
      sentry: {
        enabled: true,
        config: {
          dsn: env('SENTRY_DSN'),
          sendMetadata: true,
        },
      },
      'transformer': {
        enabled: true,
        config: {
          prefix: '/api/',
          responseTransforms: {
            removeAttributesKey: true,
            removeDataKey: true,
          }
        }
      },
      'import-export-entries': {
        enabled: true,
      },
    });
    
    opened by gdSuhail 5
  • deep relations don't work

    deep relations don't work

    Tested with and without the plugin, deep relations don't seems to work with the plugin turned on.

    like if i retrieve posts content-type with user relation, it would work

    But if i try to retrieve user's relation like user.profilePic, it won't work

    bug 
    opened by Nisthar 5
  • Feature Request: Add Grapghql response transformer

    Feature Request: Add Grapghql response transformer

    Since this plugin mainly used to reduce unnessary nested object for api. Need same feature for graphql.

    Since graphql return body as string, that transform logic doesn't allowed to transform.

    Below code change is to add logic for grapghql.

    if (isAPIRequest(ctx)) {
    	const { data } = ctx.body;
    
    	// ensure no error returned.
    	if (data) {
    		ctx.body['data'] = getPluginService('transformService').response(settings, data);
    	}
    }
    

    to

    if (isAPIRequest(ctx)) {
    	if(_.isString(ctx.body)){
    		ctx.body = JSON.parse(ctx.body);
    	}
    	const { data } = ctx.body;
    
    	// ensure no error returned.
    	if (data) {
    		ctx.body['data'] = getPluginService('transformService').response(settings, data);
    	}
    }
    
    opened by rupekeshan 4
  • Not supported in new strapi versions

    Not supported in new strapi versions

    Not supported in new strapi versions. Supported in Node Versions- "engines": { "node": ">=14.19.1 <=16.x.x", "npm": ">=6.0.0" },

    Not Supported in Latest Versions- "engines": { "node": ">=14.19.1 <=18.x.x", "npm": ">=6.0.0" },

    opened by bis0072 3
  • Feature request: wrapping POST or PUT requests' body within `data` key if not

    Feature request: wrapping POST or PUT requests' body within `data` key if not

    Background

    When we send a POST or PUT request to a content API, Strapi asks us to wrap the object in a data key, which is also tedious like data keys in responses.

    GOOD:

    {
    	"data": {
    		"name": "foo bar"
    	}
    }
    

    BAD:

    {
    	"name": "foo bar"
    }
    

    The "BAD" example will get an error response, like this:

    {
        "error": {
            "status": 400,
            "name": "ValidationError",
            "message": "Missing \"data\" payload in the request body"
        }
    }
    

    Behavior

    Auto wraps the body of requests within a data key, transforming the "BAD" example above to the "GOOD" one.

    I suppose we can do this in the middleware, too.

    Config

    I propose a new config key:

    | Property | Description | Type | Default | Required | | -------- | ----------- | ---- | ------- | -------- | | requestTransforms | The transformations to enable for the API request | Object | undefined | No | | requestTransforms.wrapWithDataKey | Wraps the request body with data key if needed | Boolean | false | No |


    Love this plugin. Thank you for your excellent work!

    I can compose a PR if you like this proposal. :wink:

    enhancement 
    opened by cssmagic 4
Releases(2.1.1)
  • 2.1.1(Nov 22, 2022)

    What's Changed

    • fix(pkg.json): node engine version mismatch by @ComfortablyCoding in https://github.com/ComfortablyCoding/strapi-plugin-transformer/pull/48

    Full Changelog: https://github.com/ComfortablyCoding/strapi-plugin-transformer/compare/2.1.0...2.1.1

    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Aug 24, 2022)

    What's Changed

    • feat(transform): skip requests with Strapi-Transformer-Ignore header as true by @ComfortablyCoding in https://github.com/ComfortablyCoding/strapi-plugin-transformer/pull/39

    Full Changelog: https://github.com/ComfortablyCoding/strapi-plugin-transformer/compare/2.0.2...2.1.0

    Source code(tar.gz)
    Source code(zip)
  • 2.0.2(Jun 8, 2022)

    What's Changed

    • fix(isAPIRequest): ensure all routes are content-api by @ComfortablyCoding in https://github.com/ComfortablyCoding/strapi-plugin-transformer/pull/26

    Full Changelog: https://github.com/ComfortablyCoding/strapi-plugin-transformer/compare/2.0.1...2.0.2

    Source code(tar.gz)
    Source code(zip)
  • 2.0.1(Apr 8, 2022)

    What's Changed

    • fix(transformResponse) handle empty relational data by @ComfortablyCoding in https://github.com/ComfortablyCoding/strapi-plugin-transformer/pull/19
    • chore(README): add create config file note by @ComfortablyCoding in https://github.com/ComfortablyCoding/strapi-plugin-transformer/pull/21

    Full Changelog: https://github.com/ComfortablyCoding/strapi-plugin-transformer/compare/2.0.0...2.0.1

    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Mar 20, 2022)

    What's Changed

    • feat(responseTransform) add removeDataKey option by @ComfortablyCoding in https://github.com/ComfortablyCoding/strapi-plugin-transformer/pull/16

    Full Changelog: https://github.com/ComfortablyCoding/strapi-plugin-transformer/compare/1.0.3...2.0.0

    Source code(tar.gz)
    Source code(zip)
  • 1.0.3(Feb 18, 2022)

    This release introduces the following changes:

    • fix repeatable components #7
    • add test suite
    • rename index to removeAttributeKey
    • add badges to the README
    • add automated testing workflows

    Full Changelog: https://github.com/ComfortablyCoding/strapi-plugin-transformer/compare/1.0.2...1.0.3

    Source code(tar.gz)
    Source code(zip)
  • 1.0.2(Feb 17, 2022)

    This release introduces the following changes:

    • fixes not accounting for multiple entity relations on a content type.
    • ensure ctx.body exists before attempting processing.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Feb 11, 2022)

    This release introduces the following changes:

    • fixed plugin name should match with strapi.name value in packge.json
    • fixed incorrect json syntax for examples
    • removed dead code
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Feb 11, 2022)

A plugin for Strapi that provides the ability to easily schedule publishing and unpublishing of any content type

strapi-plugin-publisher A plugin for Strapi that provides the ability to easily schedule publishing and unpublishing of any content type. Requirements

daedalus 19 Dec 7, 2022
A plugin for Strapi that provides the ability to auto slugify a field for any content type

strapi-plugin-slugify A plugin for Strapi that provides the ability to auto slugify a field for any content type. It also provides a findOne by slug e

daedalus 25 Nov 28, 2022
A plugin for Strapi CMS that adds a preview button and live view button to the content manager edit view.

Strapi Preview Button A plugin for Strapi CMS that adds a preview button and live view button to the content manager edit view. Get Started Features I

Matt Milburn 53 Dec 30, 2022
a vscode extension for http response data auto transform ts type.

Api2ts 这是一个自动将 http 的响应数据转化为 ts 的类型,使用 json-to-ts 做的。 Features 框选配置项后,使用快捷键 alt+Q : 请求参数配置文件 在根目录下创建 Api2ts.config.json 文件,配置项如下: { "baseURL": "http

phy-lei 6 Jun 30, 2022
Modify Request & Response Headers Chrome Extension (Manifest V3)

Modify request & response headers (Chrome Extension Manifest V3) This Chrome extension will add request header and response header to few network requ

Requestly 6 Dec 9, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A request library that returns promises, inspired by request

then-request A request library that returns promises and supports both browsers and node.js Installation npm install then-request Usage request(metho

then (Promises/A+ implementations) 241 Nov 29, 2022
Gatsby-blog-cosmicjs - 🚀⚡️ Blazing fast blog built with Gatsby and the Cosmic Headless CMS 🔥

Gatsby + Cosmic This repo contains an example blog website that is built with Gatsby, and Cosmic. See live demo hosted on Netlify Uses the Cosmic Gats

Priya Chakraborty 0 Jan 29, 2022
Update & Revalidate Content from a Headless CMS in Next.js with Incremental Static Regeneration

Update & Revalidate Content from a Headless CMS in Next.js with Incremental Static Regeneration Demo for tutorial How to Update & Revalidate Content f

Colby Fayock 4 Jul 22, 2022
🛠 Building a Headless CMS with all the essential features for business representative websites to make 🚀

Isomera - headless CMS for business representative websites SaaS that is hosted on the cloud and built by community. To make developer life easy. ⚠️ A

Cortip 8 Dec 3, 2022
The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling rapid development of iofod extensions through the SDK.

iofod-sdk English | 简体中文 The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling

iofod, Inc. 47 Oct 17, 2022
Pfapi plugin uses local and redis caches to achieve single digit milliseconds on average api response time.

Strapi plugin pfapi Pfapi plugin provides configurable, secure and fast API services. APIs are configurable through the admin panel with components an

null 5 Sep 17, 2022
💰The Shopify-like Digital Commerce engine provides an Open-Source 🆓 and Headless/Modular Architecture ⚡

?? The Shopify-like Digital Commerce ⚡ ?? The Shopify-like Digital Commerce engine provides an Open-Source ?? and Serverless Architecture ⚡ ?? The Sho

OceanSoft 7 Nov 7, 2022
A jQuery plugin to submit forms with files via AJAX and to get a response with errors.

jquery-ajaxform A jQuery plugin to submit form with files via AJAX and to get a response with errors. Browsers without FormData uses iframe transport

gozoro 2 Mar 30, 2021
Uptime monitoring RESTful API server that allows authenticated users to monitor URLs, and get detailed uptime reports about their availability, average response time, and total uptime/downtime.

Uptime Monitoring API Uptime monitoring RESTful API server that allows authenticated users to monitor URLs, and get detailed uptime reports about thei

Mohamed Magdi 2 Jun 14, 2022
Strapi V4 Plugin to schedule publish and depublish actions

Strapi plugin scheduler This plugin allows you to publish and depublish collection types in the future. There are a couple of steps necessary to get t

Webbio 12 Nov 24, 2022
Basic types & utilities for Strapi v4 and plugin creators

Strapi v4 - Types & utilities Basic set of types and utilities for Strapi v4 and plugins creators A developers goodie for Strapi Headless CMS which pr

 VirtusLab Open-Source 7 Oct 14, 2022