GithubHelp home page GithubHelp logo

comfortablycoding / strapi-plugin-transformer Goto Github PK

View Code? Open in Web Editor NEW
137.0 4.0 19.0 113 KB

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

Home Page: https://market.strapi.io/plugins/strapi-plugin-transformer

License: MIT License

JavaScript 100.00%
strapi strapi-plugin plugin transform response

strapi-plugin-transformer's Introduction

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.

Support

IMPORTANT: GraphQL is not supported, see #23 and #13 for additional context.

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 exist, you will need to create it.

Minimal Configuration

module.exports = ({ env }) => ({
  // ..
 'transformer': {
    enabled: true,
    config: {}
  },
  // ..
});

Sample configuration

module.exports = ({ env }) => ({
  // ..
 'transformer': {
    enabled: true,
    config: {
      responseTransforms: {
        removeAttributesKey: true,
        removeDataKey: true,
      },
      requestTransforms : {
        wrapBodyWithDataKey: true
      },
      hooks: {
        preResponseTransform : (ctx) => console.log('hello from the preResponseTransform hook!'),
        postResponseTransform : (ctx) => console.log('hello from the postResponseTransform hook!')
      },
      contentTypeFilter: {
        mode: 'allow',
        uids: {
          'api::article.article': true,
          'api::category.category': {
            'GET':true,
          }
        }
      },
      plugins: {
        ids: {
          'slugify': true,
        }
      }
    }
  },
  // ..
});

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

The Complete Plugin Configuration Object

Property Description Type Default Required
responseTransforms The transformations to enable for the API response Object N/A 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
requestTransforms The transformations to enable for an API request Object N/A No
requestTransforms.wrapBodyWithDataKey Auto wraps the body of PUT and POST requests with a data key Boolean false No
hooks The hooks to enable for the plugin Object N/A No
hooks.preResponseTransform A hook that executes before the Response Transforms are applied Function () => {} No
hooks.postResponseTransform A hook that executes after the Response Transforms are applied Function () => {} No
contentTypeFilter The content types to deny or allow the middleware to be registered on. Defaults to allow all content types Object N/A No
contentTypeFilter.mode The filter mode. The current supported modes are none, allow or deny String 'none' No
contentTypeFilter.uids The uids to filter Object {} No
plugins The plugins to deny or allow the middleware to be registered on. Defaults to deny all plugins Object N/A No
plugins.mode The filter mode. The current supported modes are none, allow or deny String 'none' No
plugins.ids The plugin ids to filter. The plugin id is the name you set in the plugins.js file Object {} 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": {},
}

Auto wrap the body content with a data key

This request transform will auto wrap the body content with a surrounding data key on all enabled routes.

Before

{
  "title": "Lorem Ipsum",
}

After

{
  "data": {
    "title": "Lorem Ipsum",
  }
}

Supported Headers

Name Description Type Default Required
Strapi-Transformer-Ignore Indicates if transform should be ignored for this request String 'false' No

CORS

By default, CORS will block any custom headers. To enable custom headers to be accepted the cors middlware headers property must include the custom header(s) that should be accepted.

Example CORS configuration

module.exports = [
  // ..
  {
    name: 'strapi::cors',
    config: {
      headers: ['Strapi-Transformer-Ignore'],
    },
  },
  // ..
]

Bugs

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

strapi-plugin-transformer's People

Contributors

ayhandoslu avatar comfortablycoding avatar cssmagic avatar jaydeesale avatar karlkeefer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

strapi-plugin-transformer's Issues

Config not being set correctly

Trying to use the plugin, seems strapi config is not being set correctly.

module.exports = ({ env }) => ({ // .. transformer: { enabled: true, config: { responseTransforms: { removeAttributesKey: true, removeDataKey: true, }, requestTransforms: { wrapBodyWithDataKey: true, }, hooks: { preResponseTransform: (ctx) => console.log("hello from the preResponseTransform hook!"), postResponseTransform: (ctx) => console.log("hello from the postResponseTransform hook!"), }, contentTypeFilter: { mode: "allow", uids: { "api::article.article": true, "api::category.category": { GET: true, }, }, }, }, }, // .. });

above is the config/plugin.ts file, and when i get to the plugin itself seems im getting back only the hooks object causing the middleware not to register

{ hooks: { preResponseTransform: [Function: preResponseTransform], postResponseTransform: [Function: postResponseTransform] } } plugin.transformer

response from the settings-service.ts

`'use strict';

const { pluginId } = require('../util/pluginId');

module.exports = ({ strapi }) => ({
get() {
const value = strapi.config.get(plugin.${pluginId});
console.log("WTF", value, plugin.${pluginId})
return value
},
});`

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 🙇‍♀️.

Option to remove toplevel `data` attribute (and `meta` attribute)

I am new to strapi. I use it with next.js. I already added you plugin (thanks!). However, I noticed that the toplevel data is still there, even with removeDataKey: true. So responses come as

{
  data: { ...my actual data... }
  meta: { always empty }
}

In my opinion it would be nice if the top level data and also the meta could also be removed.

In my next.js app with the redux-toolkit I always have to write an extra data:

  const { data, error, isLoading } = useGetContentByIdQuery(id);

  return (
          <MyContent
              attr1={data.data.att1}
              attr2={data.data.att2}
            />
  );

So the typing of the response also has an unneeded data.

Now it is:

type MyContentType= {
  data: {
    id: number;
    createdAt: string;
    updatedAt: string;
    publishedAt: string;
    att1: string;
    att2: string;
  };
  meta: {};
};

But it should imho rather be:

type MyContentType= {
    id: number;
    createdAt: string;
    updatedAt: string;
    publishedAt: string;
    att1: string;
    att2: string;
};

hook example

Hi,

I was looking for an example on how to use ˋhooks.postResponseTransform(ctx)` method, would you have one?

thank you

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: strapi-community/strapi-plugin-rest-cache#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.

[FEAT] Transformations are not visible in Documentation plugin

We are using this plugin to avoid that much nestedness coming from Strapi 4.

It works fine.

When we want to work the API on Frontend we need the documentation plugin so we know what are we getting for any API request.

The problem is, that we don't see any changes done by the transformer in the documentation,
image

Here is our configuration:

  transformer: {
    enabled: true,
    config: {
      responseTransforms: {
        removeAttributesKey: true,
        removeDataKey: true,
      },
      requestTransforms: {
        wrapBodyWithDataKey: true,
      },
    },
  },

Why?

Custom Path for content-type not registering middleware in v3.0

If I provide a custom path in a content-type's custom route configuration, this plugin, as of v3.0, does not see that custom path when registering the middleware. It worked fine in v2.2.0.

I believe the issue is that Strapi does not give you the custom path in this call:
const apis = _.get(strapi, ['api'], {}); in the register.js

Example of custom path in custom route:

add new .js in the content-type's route folder, called '01-custom.js'. Add

// 01-custom.js
module.exports = {
  routes: [
    {
      method: "GET",
      path: "/myrestaurants",
      handler: "restaurants.find",
      config: {
        description: "Returns restaurants.",
        policies: [],
      },
    },
  ],
};

Appreciate the work on this plugin and hopefully we can find a way to do this so we can utilize v3 with other plugins like the rest-cache one.

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"
  

Getting error after adding the config.js

I am adding the same config as it has been stated in documentation and I am getting the following error:
The "path" argument must be of type string. Received undefined

Documentation (swagger) not updated

Work, well play, i search for it then i found this project on the strapi market place :)

But ...
image

On my documentation (swagger) , i can see Data and Attributes object, possible to change swagger too ?

Thanks

Not working - strapi v 4.24

Following the documentation, I copied the Sample configuration and installed it, but it is not working and the output is the same as before.
node: v18.19.1
OS: Ubuntu 24.04 LTS
strapi: v4.24.4
image

Screenshot 2024-06-17 200155

[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)?

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 👍

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

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);
	}
}

[bug] custom collections are not transformed

Hello,

Thank you for all the work you do on this package. I just upgraded from 2.2.0 to 3.0.1, and I am noticing that my collection types with custom route files such as:

01-collection-type-example.ts
02-collection-type-example.ts

Are now not working.

Please let me know if there is any other information I can provide!

Error de Login

El plugin es genial! Me reestructura los datos de respuestas de una manera más óptima y legible. Pero por algún motivo no podía hacer login. Probé muchas cosas y después de muchas horas, pude detectar que lo que me generaba un error 400, ya que me decía que no había puesto el identifier ni el password en el body de la ruta http://localhost:1337/api/auth/local
Pero siempre lo ponía sin falta. Pero al remover este paquete pude realizar el auth sin problema alguno.
// ..
'transformer': {
enabled: true,
config: {
responseTransforms: {
removeAttributesKey: true,
removeDataKey: true,
},
requestTransforms: {
wrapBodyWithDataKey: true
},
hooks: {
preResponseTransform: (ctx) => console.log('hello from the preResponseTransform hook!'),
postResponseTransform: (ctx) => console.log('hello from the postResponseTransform hook!')
},
contentTypeFilter: {
mode: 'allow',
uids: {
'api::categoria.categoria': true
}
},
plugins: {
ids: {
'slugify': true,
}
}
}
},
así tenía la configuración del plugin.js y me encantaría que me orientaran en caso de que lo haya aplicado mal o que corrijan el error en caso de defecto de plugin. Este plugin me gustó pero al presentarse este error y falta de explicación, ya que soy un novato aún con esto y la documentación no me ha ayudado tanto, un vídeo si es posible sería grandioso explicando como usar este plugin de forma eficiente.

Plugin configuration needs to be inside .config/env/

Many people have reported problems with the plugin not working as documented. I had the same problem. I installed the plugin. Added ./config/plugins.js file as documented and nothing happened.

I found out that plugins.js file inside ./config folder is ignored by Strapi at least in the case you are having a ./config/env folder.

See: https://github.com/strapi/strapi/blob/d999ad0b00ff427885462051cdc96626b7946472/packages/core/strapi/src/core/app-configuration/index.ts#L54

I managed to fix the issue by moving the plugins.js file inside my env folder's respective environment folders (development, production, ...).

Like this.

Before:

./config
  plugins.js

After:

./config
  /env
    /development
      plugins.js
    /production
      plugins.js

Could you add this to the documentation?

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"
},

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"
},

'prefix' not applying on V2.2.0 and Strapi V4.5.5

Hi there,

Great plugin! This was extremely handy for people who didn't want Strapi V4's unnecessary data / attributes nesting system.

However, whilst trying to modify the value of "prefix" in my plugin configuration, it seems that none of the changes I make actually affect the resolved prefix when I start the application.

Each time, I delete the .cache and build folder, and run a clean strapi build, nothing seems to make a difference.

Here's my full plugins.js file, so you can see the other plugins I use:

module.exports = ({ env }) => ({
  transformer: {
    enabled: true,
    config: {
      prefix: '/testtest/',
      responseTransforms: {
        removeAttributesKey: true,
        removeDataKey: true
      }
    }
  },
  ckeditor: {
    enabled: true,
    config: {
      editor: {
        link: {
          addTargetToExternalLinks: true,
          decorators: {
            openInNewTab: {
              mode: 'manual',
              label: 'Open in a new tab',
              defaultValue: true,
              attributes: {
                target: '_blank',
                rel: 'noopener noreferrer'
              }
            }
          }
        }
      }
    }
  },
  upload: {
    config: {
      provider: 'aws-s3',
      providerOptions: {
        accessKeyId: env('AWS_ACCESS_KEY_ID'),
        secretAccessKey: env('AWS_ACCESS_SECRET'),
        region: env('AWS_REGION'),
        params: {
            Bucket: env('AWS_BUCKET_NAME'),
        },
      },
      // These parameters could solve issues with ACL public-read access — see [this issue](https://github.com/strapi/strapi/issues/5868) for details
      actionOptions: {
        upload: {
          ACL: null
        },
        uploadStream: {
          ACL: null
        },
      }
    },
  }
});

And here's all of my dependencies from package.json, so you can see what else I'm working with:

"dependencies": {
    "@_sh/strapi-plugin-ckeditor": "^1.1.2",
    "@strapi/plugin-documentation": "4.5.5",
    "@strapi/plugin-graphql": "4.5.5",
    "@strapi/plugin-i18n": "4.5.5",
    "@strapi/plugin-users-permissions": "4.5.5",
    "@strapi/provider-upload-aws-s3": "4.5.5",
    "@strapi/strapi": "4.5.5",
    "axios": "^0.24.0",
    "better-sqlite3": "^7.6.2",
    "i": "^0.3.7",
    "jsonwebtoken": "^8.5.1",
    "jwk-to-pem": "^2.0.5",
    "knex": "0.21.18",
    "npm": "^9.2.0",
    "pg": "^8.7.1",
    "strapi-plugin-ckeditor5": "^1.14.0",
    "strapi-plugin-transformer": "^2.2.0"
  },

Here's a couple of screenshots showing it not working as intended:
image
image

It would be fantastic if you could find / fix the issue that's going on here! I'll happily provide any other info you might need.

For context, I'm using AWS Cloudfront and a reverse proxy to host the frontend and backend under the same URL. Anything that's api/* defaults to the Strapi backend. This worked on V3, but upgrading to V4 has caused our endpoints to now become api/api/articles, which we expected.

If I can't outright get rid of the second /api/, then I'll just rename it to /api/v1/*, so it doesn't look as bad.

Thanks in advance for any help / advice you can provide!

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. 😉

[FR] add hook support

Request

Add pre and post transform hooks for users to utilize for any additional modifications they wish to make.

Example

module.exports = ({ env }) => ({
  // ..
 'transformer': {
    enabled: true,
    config: {
      // ...
      hooks :{
       'preResponseTransform': (ctx)=>{}
       'postResponseTransform': (ctx)=>{}
      }
      // ...
    }
  },
  // ..
});

P.S. Brought up in #46.

[BUG] repeatable component with nested component that contains a relation is not transformed

transformer: {
  enabled: true,
  config: {
    responseTransforms: {
      removeAttributesKey: true,
      removeDataKey: true,
    },
    requestTransforms : {
      wrapBodyWithDataKey: true,
    },
  },
}

image

image

Relation type "oneToOne".

Response example:

{
  "size": [ // Component "size"
    {
      "id": 1,
      "length": 90,
      "width": 60,
      "height": 5,
      "price": 15000,
      "stand": { // Nested component "size.stand"
        "id": 1,
        "additionalProducts": { // Relation field (oneToOne)
          "data": { // not deleted
            "id": 3,
            "attributes": { // not deleted
              "title": "Тумба 70x20x20",
              "description": "Описание тумбы 70x20x20",
              "price": 2000,
              "createdAt": "2024-01-06T11:30:46.980Z",
              "updatedAt": "2024-01-06T11:30:49.477Z",
              "publishedAt": "2024-01-06T11:30:49.384Z",
              "locale": "ru"
            }
          }
        }
      }
    }
  ]
}

Request to include modifyResponseBodyData as an available service method

Hello and thank you for all your work on this plugin! Also hope you are feeling better after being sick recently 🙂 (just noticed in issue comments)

I recently went to upgrade from a v2 version of the plugin to v3 and realized I was relying on the previous version of the plugin's response service method in one of my app's custom middlewares but now it seems that is not possible to use directly from the plugin.

After reviewing the latest version of the plugin, do you think it would be possible to make the modifyResponseBodyData util function an available service method?

Background and Example
In my app, I have some Pages which can have parent pages and some have more than one parent page. For the API response data, I'm using a middleware which finds the root parent page and appends it to the response data, but it's using the old response method from the transformer plugin to sanitize the new data.

const plugin = strapi.plugin( 'transformer' );
const settings = plugin.service( 'settingsService' ).get();
const transform = plugin.service( 'transformService' );

// Find the root page to append to the response data.
const rootPage = await strapi.query( 'api::page.page' ).findOne( {
  where: {
    slug: 'example-root-page',
  },
} );

// Format data so it uses data and attributes, then let the transformer plugin deal with it according to plugin settings.
const rootPageData = {
  data: {
    id: rootPage.id,
    attributes: omit( rootPage, [ 'id' ] ),
  },
};

// Final result.
const entityWithExtras = {
   ...entity, // assume the `entity` object is already defined.
   root_page: transform.response( settings, rootPage ),
};

TypeError: Cannot read properties of undefined (reading 'uid')

After installing your plugin, I was trying to deploy on Digital Ocean, I kept getting a build failure. Saw an error and then tried starting Strapi locally and got same error:

TypeError: Cannot read properties of undefined (reading 'uid')
    at Object.module.exports [as register] (/Volumes/Strapi/api/node_modules/strapi-plugin-transformer/server/register.js:26:41)
    at Object.register (/Volumes/Strapi/api/node_modules/@strapi/strapi/lib/core/domain/module/index.js:47:46)
    at Object.register (/Volumes/Strapi/api/node_modules/@strapi/strapi/lib/core/registries/modules.js:33:19)
    at async Strapi.runLifecyclesFunctions (/Volumes/Strapi/api/node_modules/@strapi/strapi/lib/Strapi.js:541:5)
    at async Strapi.register (/Volumes/Strapi/api/node_modules/@strapi/strapi/lib/Strapi.js:401:5)
    at async Strapi.load (/Volumes/Strapi/api/node_modules/@strapi/strapi/lib/Strapi.js:487:5)
    at async Strapi.start (/Volumes/Strapi/api/node_modules/@strapi/strapi/lib/Strapi.js:217:9)

Using Strapi v4.6.1 - Node v16.19.1 - NPM v8.6.3

[EDIT] I added a console.log at line 26 of your register.js file and it looks like UID is not available on one of my collection types:

[Edit2] It is there, sorry. I'll research a little more before posting more info.

[bug] api prefix and admin clash causes admin to break

Hello, I followed the settings correctly, and everything went right.

I created the plugins.js added the settings, and sent the settings via environment variables.

External API working perfectly.

But when I went to access the Content Type, I'm getting this error message:

image

And it doesn't load the Content Types, and the contents I have are gone:

image

I'm using strapi 4.1.12

And my settings:

image
image

If I disable the settings everything goes back to normal.
And I'm uploading the strapi with:

yarn strapi develop --watch-admin

I would love to use this extension, but with this problem I can't use it, did I miss some configuration?

Thanks for the help.

remove "data" property from JSON Datatype

To reproduce:

  1. Create a collection with JSON field
  2. Insert in JSON field the content: [{"data": 1}, {"data": "test"}]
  3. Transform remove "data" from JSON content.

This isn't a relation field.

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

Error relation transform

``Hello,

I have noticed that in case of multiple relation, your service algo don't work correctly.

Can you update :
const key = _.findKey(data, (p) => p && !Array.isArray(p) && p.data); if (key) { data[key] = transform(data[key].data); }

With :
_.keys(data).forEach((key) => { if (data[key] && !Array.isArray(data[key]) && data[key].data !== undefined) { data[key] = transform(data[key].data); } })

;)

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

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,
  },
});

Error multiple component transform

Hello,

It's me again ^^'

I noticed that in the case of using multiple components (reusable), the transformation does not apply.

I think that instead of :

		_.forEach(data, (value, key) => {
			if (value && !Array.isArray(value) && value.data) {
				data[key] = transform(value.data);
			}
		});

It should be put :

		_.forEach(data, (value, key) => {
			if (value && !Array.isArray(value) && value.data) {
				data[key] = transform(value.data);
			} else if (value && Array.isArray(value)) {
				data[key] = data[key].map((e) => transform(e))
			}
		});

Update yup to v1 branch

Current version of strapi-plugin-transformer uses old version of yup (branch 0.x.x), which causes conflicts with other plugins.

here is release notes to v1: jquense/yup#1906

DenyList is not working in my strapi project

I added strapi-plugin-transfomer to my strapi project and it is working, But I need to exclude some content types apis from being transformed.
Currently I added the denylist and all apis are transformed including ones in the denylist.
Strapi Version: 4.4.5
Plugin Version: 3.0.0
plugins.ts

export default ({ env }) => ({
  'transformer': {
     enabled: true,
     config: {
       prefix: '',
       responseTransforms: {
         removeAttributesKey: true,
         removeDataKey: true,
       },
       denyList: {
        'api::service.service': true,
      }
     }
   },
   upload: {
    config: {
      breakpoints: {
        xlarge: 1920,
        large: 1000,
        medium: 750,
        small: 500,
        xsmall: 64
      },
    },
  },
 });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.