Compare commits

...

7 Commits

Author SHA1 Message Date
DanielPantle
f7843ee318
docs: add note regarding compound slug (#123)
* Update README.md

Include note that multiple fields are possible as reference

* update wording

---------

Co-authored-by: daedalus <44623501+ComfortablyCoding@users.noreply.github.com>
2024-01-16 23:28:54 -05:00
daedalus
65c3a4e5f0
chore(release): 2.3.8 (#121) 2023-11-19 11:19:34 -05:00
daedalus
66b9d2789c
fix(graphql): errors should not result in internal error (#120) 2023-11-19 11:17:44 -05:00
daedalus
68ea256e5b
chore(release): 2.3.7 (#119) 2023-11-14 19:57:32 -05:00
daedalus
5752ccfc93 fix(controller): errors should not result in internal error 2023-11-14 19:55:55 -05:00
daedalus
f7ba4cce37 chore: update deps 2023-11-14 19:55:55 -05:00
daedalus
430f90b992 refactor(slugController): internalise transform
Resolves #108
2023-11-14 19:55:55 -05:00
7 changed files with 8792 additions and 93 deletions

View File

@ -54,7 +54,9 @@ module.exports = ({ env }) => ({
This will listen for any record created or updated in the article content type and set a slugified value for the slug field automatically based on the title field. This will listen for any record created or updated in the article content type and set a slugified value for the slug field automatically based on the title field.
> Note that if you want to rewrite the same field (so `title` is both a reference and a slug) then you just put `title` for both the `field` and `references` properties. > Note: To rewrite the same field (e.g. `title` is both a reference and a slug) use `title` as the `field` and `references` value.
> Note: Compound slugs (basing the slug on multiple fields) can be achieved by passing an array of fields to the `references` property (e.g. `references: ['date','title']`).
**IMPORTANT NOTE**: Make sure any sensitive data is stored in env files. **IMPORTANT NOTE**: Make sure any sensitive data is stored in env files.

View File

@ -1,7 +1,7 @@
{ {
"$schema": "https://json.schemastore.org/package", "$schema": "https://json.schemastore.org/package",
"name": "strapi-plugin-slugify", "name": "strapi-plugin-slugify",
"version": "2.3.6", "version": "2.3.8",
"description": "A plugin for Strapi Headless CMS that provides the ability to auto slugify a field for any content type.", "description": "A plugin for Strapi Headless CMS that provides the ability to auto slugify a field for any content type.",
"scripts": { "scripts": {
"lint": "eslint . --fix", "lint": "eslint . --fix",
@ -26,20 +26,18 @@
"url": "https://github.com/ComfortablyCoding/strapi-plugin-slugify/issues" "url": "https://github.com/ComfortablyCoding/strapi-plugin-slugify/issues"
}, },
"dependencies": { "dependencies": {
"@sindresorhus/slugify": "1.1.0" "@sindresorhus/slugify": "1.1.0",
},
"devDependencies": {
"eslint": "^8.52.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-node": "^11.1.0",
"prettier": "^3.0.3"
},
"peerDependencies": {
"@strapi/strapi": "^4.14.0", "@strapi/strapi": "^4.14.0",
"@strapi/utils": "^4.14.0", "@strapi/utils": "^4.14.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"yup": "^0.32.9" "yup": "^0.32.9"
}, },
"devDependencies": {
"eslint": "^8.53.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-node": "^11.1.0",
"prettier": "^3.1.0"
},
"strapi": { "strapi": {
"displayName": "Slugify", "displayName": "Slugify",
"name": "slugify", "name": "slugify",

View File

@ -1,12 +1,11 @@
'use strict'; 'use strict';
const _ = require('lodash'); const _ = require('lodash');
const { NotFoundError } = require('@strapi/utils').errors;
const { getPluginService } = require('../utils/getPluginService'); const { getPluginService } = require('../utils/getPluginService');
const { transformResponse } = require('@strapi/strapi/dist/core-api/controller/transform');
const { isValidFindSlugParams } = require('../utils/isValidFindSlugParams'); const { isValidFindSlugParams } = require('../utils/isValidFindSlugParams');
const { sanitizeOutput } = require('../utils/sanitizeOutput'); const { sanitizeOutput } = require('../utils/sanitizeOutput');
const { hasRequiredModelScopes } = require('../utils/hasRequiredModelScopes'); const { hasRequiredModelScopes } = require('../utils/hasRequiredModelScopes');
const transform = require('../utils/transform');
module.exports = ({ strapi }) => ({ module.exports = ({ strapi }) => ({
async findSlug(ctx) { async findSlug(ctx) {
@ -14,15 +13,23 @@ module.exports = ({ strapi }) => ({
const { modelName, slug } = ctx.request.params; const { modelName, slug } = ctx.request.params;
const { auth } = ctx.state; const { auth } = ctx.state;
isValidFindSlugParams({ try {
modelName, isValidFindSlugParams({
slug, modelName,
modelsByName, slug,
}); modelsByName,
});
} catch (error) {
return ctx.badRequest(error.message);
}
const { uid, field, contentType } = modelsByName[modelName]; const { uid, field, contentType } = modelsByName[modelName];
await hasRequiredModelScopes(strapi, uid, auth); try {
await hasRequiredModelScopes(strapi, uid, auth);
} catch (error) {
return ctx.forbidden();
}
// add slug filter to any already existing query restrictions // add slug filter to any already existing query restrictions
let query = ctx.query || {}; let query = ctx.query || {};
@ -40,9 +47,9 @@ module.exports = ({ strapi }) => ({
if (data) { if (data) {
const sanitizedEntity = await sanitizeOutput(data, contentType, auth); const sanitizedEntity = await sanitizeOutput(data, contentType, auth);
ctx.body = transformResponse(sanitizedEntity, {}, { contentType }); ctx.body = transform.response({ data: sanitizedEntity, schema: contentType });
} else { } else {
throw new NotFoundError(); ctx.notFound();
} }
}, },
}); });

View File

@ -3,6 +3,7 @@ const { getPluginService } = require('../utils/getPluginService');
const { isValidFindSlugParams } = require('../utils/isValidFindSlugParams'); const { isValidFindSlugParams } = require('../utils/isValidFindSlugParams');
const { hasRequiredModelScopes } = require('../utils/hasRequiredModelScopes'); const { hasRequiredModelScopes } = require('../utils/hasRequiredModelScopes');
const { sanitizeOutput } = require('../utils/sanitizeOutput'); const { sanitizeOutput } = require('../utils/sanitizeOutput');
const { ForbiddenError, ValidationError } = require('@strapi/utils').errors;
const getCustomTypes = (strapi, nexus) => { const getCustomTypes = (strapi, nexus) => {
const { naming } = getPluginService('utils', 'graphql'); const { naming } = getPluginService('utils', 'graphql');
@ -54,16 +55,23 @@ const getCustomTypes = (strapi, nexus) => {
const { modelName, slug, publicationState } = args; const { modelName, slug, publicationState } = args;
const { auth } = ctx.state; const { auth } = ctx.state;
isValidFindSlugParams({ try {
modelName, isValidFindSlugParams({
slug, modelName,
modelsByName, slug,
publicationState, modelsByName,
}); publicationState,
});
} catch (error) {
throw new ValidationError(error.message);
}
const { uid, field, contentType } = modelsByName[modelName]; const { uid, field, contentType } = modelsByName[modelName];
await hasRequiredModelScopes(strapi, uid, auth); try {
await hasRequiredModelScopes(strapi, uid, auth);
} catch (error) {
throw new ForbiddenError();
}
// build query // build query
let query = { let query = {

View File

@ -1,12 +1,5 @@
const { ForbiddenError } = require('@strapi/utils').errors; const hasRequiredModelScopes = (strapi, uid, auth) =>
strapi.auth.verify(auth, { scope: `${uid}.find` });
const hasRequiredModelScopes = async (strapi, uid, auth) => {
try {
await strapi.auth.verify(auth, { scope: `${uid}.find` });
} catch (e) {
throw new ForbiddenError();
}
};
module.exports = { module.exports = {
hasRequiredModelScopes, hasRequiredModelScopes,

97
server/utils/transform.js Normal file
View File

@ -0,0 +1,97 @@
'use strict';
const { isNil, isPlainObject } = require('lodash/fp');
function response({ data, schema }) {
return transformResponse(data, {}, { contentType: schema });
}
// adapted from https://github.com/strapi/strapi/blob/main/packages/core/strapi/src/core-api/controller/transform.ts
function isEntry(property) {
return property === null || isPlainObject(property) || Array.isArray(property);
}
function isDZEntries(property) {
return Array.isArray(property);
}
function transformResponse(resource, meta = {}, opts = {}) {
if (isNil(resource)) {
return resource;
}
return {
data: transformEntry(resource, opts?.contentType),
meta,
};
}
function transformComponent(data, component) {
if (Array.isArray(data)) {
return data.map((datum) => transformComponent(datum, component));
}
const res = transformEntry(data, component);
if (isNil(res)) {
return res;
}
const { id, attributes } = res;
return { id, ...attributes };
}
function transformEntry(entry, type) {
if (isNil(entry)) {
return entry;
}
if (Array.isArray(entry)) {
return entry.map((singleEntry) => transformEntry(singleEntry, type));
}
if (!isPlainObject(entry)) {
throw new Error('Entry must be an object');
}
const { id, ...properties } = entry;
const attributeValues = {};
for (const key of Object.keys(properties)) {
const property = properties[key];
const attribute = type && type.attributes[key];
if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {
const data = transformEntry(property, strapi.contentType(attribute.target));
attributeValues[key] = { data };
} else if (attribute && attribute.type === 'component' && isEntry(property)) {
attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);
} else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {
if (isNil(property)) {
attributeValues[key] = property;
}
attributeValues[key] = property.map((subProperty) => {
return transformComponent(subProperty, strapi.components[subProperty.__component]);
});
} else if (attribute && attribute.type === 'media' && isEntry(property)) {
const data = transformEntry(property, strapi.contentType('plugin::upload.file'));
attributeValues[key] = { data };
} else {
attributeValues[key] = property;
}
}
return {
id,
attributes: attributeValues,
// NOTE: not necessary for now
// meta: {},
};
}
module.exports = {
response,
};

8704
yarn.lock

File diff suppressed because it is too large Load Diff