Update createContentType to expose a simpler object

This commit is contained in:
Alexandre Bodin 2021-08-23 22:25:31 +02:00
parent 5f1dc39c65
commit 47c3900c07
17 changed files with 82 additions and 88 deletions

View File

@ -2,12 +2,9 @@
// eslint-disable-next-line node/no-extraneous-require
const { features } = require('@strapi/strapi/lib/utils/ee');
const executeCEBootstrap = require('../../../../server/config/functions/bootstrap');
const {
features: { sso: ssoActions },
} = require('../admin-actions');
const { getService } = require('../../../../server/utils');
const executeCEBootstrap = require('../../server/bootstrap');
const { getService } = require('../../server/utils');
const { sso: ssoActions } = require('./config/admin-actions').features;
module.exports = async () => {
const { actionProvider } = getService('permission');

View File

@ -18,7 +18,7 @@ module.exports = strapi => ({
if (isValid) {
// request is made by an admin
const admin = await strapi
.query('strapi::user')
.query('admin::user')
.findOne({ where: { id: payload.id }, populate: ['roles'] });
if (!admin || !(admin.isActive === true)) {

View File

@ -2,7 +2,7 @@
const { has, isObject } = require('lodash/fp');
const permissionModelUID = 'strapi::permission';
const permissionModelUID = 'admin::permission';
const hasAttribute = attribute => has(`attributes.${attribute}`);
const hasFieldsAttribute = hasAttribute('fields');

View File

@ -5,7 +5,7 @@
*/
module.exports = {
collectionName: 'strapi_permissions',
collectionName: 'admin_permissions',
info: {
name: 'Permission',
description: '',
@ -52,7 +52,7 @@ module.exports = {
type: 'relation',
relation: 'manyToOne',
inversedBy: 'permissions',
target: 'strapi::role',
target: 'admin::role',
},
},
};

View File

@ -5,7 +5,7 @@
*/
module.exports = {
collectionName: 'strapi_roles',
collectionName: 'admin_roles',
info: {
name: 'Role',
description: '',
@ -46,14 +46,14 @@ module.exports = {
type: 'relation',
relation: 'manyToMany',
mappedBy: 'roles',
target: 'strapi::user',
target: 'admin::user',
},
permissions: {
configurable: false,
type: 'relation',
relation: 'oneToMany',
mappedBy: 'role',
target: 'strapi::permission',
target: 'admin::permission',
},
},
};

View File

@ -5,7 +5,7 @@
*/
module.exports = {
collectionName: 'strapi_users',
collectionName: 'admin_users',
info: {
name: 'User',
description: '',
@ -79,7 +79,7 @@ module.exports = {
type: 'relation',
relation: 'manyToMany',
inversedBy: 'users',
target: 'strapi::role',
target: 'admin::role',
// FIXME: Allow setting this
collectionName: 'strapi_users_roles',
},

View File

@ -27,7 +27,7 @@ const validatePassword = (password, hash) => bcrypt.compare(password, hash);
* @param {string} options.password
*/
const checkCredentials = async ({ email, password }) => {
const user = await strapi.query('strapi::user').findOne({ where: { email } });
const user = await strapi.query('admin::user').findOne({ where: { email } });
if (!user || !user.password) {
return [null, false, { message: 'Invalid credentials' }];
@ -52,7 +52,7 @@ const checkCredentials = async ({ email, password }) => {
* @param {string} param.email user email for which to reset the password
*/
const forgotPassword = async ({ email } = {}) => {
const user = await strapi.query('strapi::user').findOne({ where: { email, isActive: true } });
const user = await strapi.query('admin::user').findOne({ where: { email, isActive: true } });
if (!user) {
return;
@ -94,7 +94,7 @@ const forgotPassword = async ({ email } = {}) => {
*/
const resetPassword = async ({ resetPasswordToken, password } = {}) => {
const matchingUser = await strapi
.query('strapi::user')
.query('admin::user')
.findOne({ where: { resetPasswordToken, isActive: true } });
if (!matchingUser) {

View File

@ -26,7 +26,7 @@ const permissionDomain = require('../../domain/permission/index');
* @returns {Promise<array>}
*/
const deleteByRolesIds = async rolesIds => {
const permissionsToDelete = await strapi.query('strapi::permission').findMany({
const permissionsToDelete = await strapi.query('admin::permission').findMany({
select: ['id'],
where: {
role: { id: rolesIds },
@ -45,7 +45,7 @@ const deleteByRolesIds = async rolesIds => {
*/
const deleteByIds = async ids => {
for (const id of ids) {
await strapi.query('strapi::permission').delete({ where: { id } });
await strapi.query('admin::permission').delete({ where: { id } });
}
};
@ -57,7 +57,7 @@ const deleteByIds = async ids => {
const createMany = async permissions => {
const createdPermissions = [];
for (const permission of permissions) {
const newPerm = await strapi.query('strapi::permission').create({ data: permission });
const newPerm = await strapi.query('admin::permission').create({ data: permission });
createdPermissions.push(newPerm);
}
@ -72,7 +72,7 @@ const createMany = async permissions => {
*/
const update = async (params, attributes) => {
const updatedPermission = await strapi
.query('strapi::permission')
.query('admin::permission')
.update({ where: params, data: attributes });
return permissionDomain.toPermission(updatedPermission);
@ -84,7 +84,7 @@ const update = async (params, attributes) => {
* @returns {Promise<Permission[]>}
*/
const findMany = async (params = {}) => {
const rawPermissions = await strapi.query('strapi::permission').findMany(params);
const rawPermissions = await strapi.query('admin::permission').findMany(params);
return permissionDomain.toPermission(rawPermissions);
};
@ -141,13 +141,13 @@ const cleanPermissionsInDatabase = async () => {
const contentTypeService = getService('content-type');
const total = await strapi.query('strapi::permission').count();
const total = await strapi.query('admin::permission').count();
const pageCount = Math.ceil(total / pageSize);
for (let page = 0; page < pageCount; page++) {
// 1. Find invalid permissions and collect their ID to delete them later
const results = await strapi
.query('strapi::permission')
.query('admin::permission')
.findMany({ limit: pageSize, offset: page * pageSize });
const permissions = permissionDomain.toPermission(results);
@ -193,7 +193,7 @@ const ensureBoundPermissionsInDatabase = async () => {
}
const contentTypes = Object.values(strapi.contentTypes);
const editorRole = await strapi.query('strapi::role').findOne({
const editorRole = await strapi.query('admin::role').findOne({
where: { code: EDITOR_CODE },
});

View File

@ -57,7 +57,7 @@ const create = async attributes => {
code: attributes.code || autoGeneratedCode,
};
return strapi.query('strapi::role').create({ data: rolesWithCode });
return strapi.query('admin::role').create({ data: rolesWithCode });
};
/**
@ -67,7 +67,7 @@ const create = async attributes => {
* @returns {Promise<role>}
*/
const findOne = (params = {}, populate) => {
return strapi.query('strapi::role').findOne({ where: params, populate });
return strapi.query('admin::role').findOne({ where: params, populate });
};
/**
@ -77,7 +77,7 @@ const findOne = (params = {}, populate) => {
* @returns {Promise<role>}
*/
const findOneWithUsersCount = async (params = {}, populate) => {
const role = await strapi.query('strapi::role').findOne({ where: params, populate });
const role = await strapi.query('admin::role').findOne({ where: params, populate });
if (role) {
role.usersCount = await getUsersCount(role.id);
@ -93,7 +93,7 @@ const findOneWithUsersCount = async (params = {}, populate) => {
* @returns {Promise<array>}
*/
const find = (params = {}, populate) => {
return strapi.query('strapi::role').findMany({ where: params, populate });
return strapi.query('admin::role').findMany({ where: params, populate });
};
/**
@ -101,7 +101,7 @@ const find = (params = {}, populate) => {
* @returns {Promise<array>}
*/
const findAllWithUsersCount = async populate => {
const roles = await strapi.query('strapi::role').findMany({ populate });
const roles = await strapi.query('admin::role').findMany({ populate });
for (let role of roles) {
role.usersCount = await getUsersCount(role.id);
}
@ -132,7 +132,7 @@ const update = async (params, attributes) => {
}
}
return strapi.query('strapi::role').update({ where: params, data: sanitizedAttributes });
return strapi.query('admin::role').update({ where: params, data: sanitizedAttributes });
};
/**
@ -141,7 +141,7 @@ const update = async (params, attributes) => {
* @returns {Promise<boolean>}
*/
const exists = async (params = {}) => {
const count = await strapi.query('strapi::role').count({ where: params });
const count = await strapi.query('admin::role').count({ where: params });
return count > 0;
};
@ -151,7 +151,7 @@ const exists = async (params = {}) => {
* @returns {Promise<number>}
*/
const count = async (params = {}) => {
return strapi.query('strapi::role').count(params);
return strapi.query('admin::role').count(params);
};
/**
@ -186,7 +186,7 @@ const deleteByIds = async (ids = []) => {
const deletedRoles = [];
for (const id of ids) {
const deletedRole = await strapi.query('strapi::role').delete({ where: { id } });
const deletedRole = await strapi.query('admin::role').delete({ where: { id } });
if (deletedRole) {
deletedRoles.push(deletedRole);
@ -201,7 +201,7 @@ const deleteByIds = async (ids = []) => {
* @param roleId
*/
const getUsersCount = async roleId => {
return strapi.query('strapi::user').count({ where: { roles: { id: roleId } } });
return strapi.query('admin::user').count({ where: { roles: { id: roleId } } });
};
/** Returns admin role

View File

@ -37,9 +37,7 @@ const create = async attributes => {
const user = createUser(userInfo);
const createdUser = await strapi
.query('strapi::user')
.create({ data: user, populate: ['roles'] });
const createdUser = await strapi.query('admin::user').create({ data: user, populate: ['roles'] });
getService('metrics').sendDidInviteUser();
@ -82,7 +80,7 @@ const updateById = async (id, attributes) => {
if (_.has(attributes, 'password')) {
const hashedPassword = await getService('auth').hashPassword(attributes.password);
return strapi.query('strapi::user').update({
return strapi.query('admin::user').update({
where: { id },
data: {
...attributes,
@ -92,7 +90,7 @@ const updateById = async (id, attributes) => {
});
}
return strapi.query('strapi::user').update({
return strapi.query('admin::user').update({
where: { id },
data: attributes,
populate: ['roles'],
@ -139,7 +137,7 @@ const isLastSuperAdminUser = async userId => {
* @returns {Promise<boolean>}
*/
const exists = async (attributes = {}) => {
return (await strapi.query('strapi::user').count({ where: attributes })) > 0;
return (await strapi.query('admin::user').count({ where: attributes })) > 0;
};
/**
@ -148,7 +146,7 @@ const exists = async (attributes = {}) => {
* @returns {Promise<registrationInfo>} - Returns user email, firstname and lastname
*/
const findRegistrationInfo = async registrationToken => {
const user = await strapi.query('strapi::user').findOne({ where: { registrationToken } });
const user = await strapi.query('admin::user').findOne({ where: { registrationToken } });
if (!user) {
return undefined;
@ -164,7 +162,7 @@ const findRegistrationInfo = async registrationToken => {
* @param {Object} params.userInfo user info
*/
const register = async ({ registrationToken, userInfo }) => {
const matchingUser = await strapi.query('strapi::user').findOne({ where: { registrationToken } });
const matchingUser = await strapi.query('admin::user').findOne({ where: { registrationToken } });
if (!matchingUser) {
throw strapi.errors.badRequest('Invalid registration info');
@ -183,7 +181,7 @@ const register = async ({ registrationToken, userInfo }) => {
* Find one user
*/
const findOne = async (where = {}, populate = ['roles']) => {
return strapi.query('strapi::user').findOne({ where, populate });
return strapi.query('admin::user').findOne({ where, populate });
};
/** Find many users (paginated)
@ -193,7 +191,7 @@ const findOne = async (where = {}, populate = ['roles']) => {
const findPage = async (query = {}) => {
const { page = 1, pageSize = 100, populate = ['roles'] } = query;
return strapi.query('strapi::user').findPage({
return strapi.query('admin::user').findPage({
where: query.filters,
_q: query._q,
populate,
@ -208,7 +206,7 @@ const findPage = async (query = {}) => {
*/
const deleteById = async id => {
// Check at least one super admin remains
const userToDelete = await strapi.query('strapi::user').findOne({
const userToDelete = await strapi.query('admin::user').findOne({
where: { id },
populate: ['roles'],
});
@ -229,7 +227,7 @@ const deleteById = async id => {
}
}
return strapi.query('strapi::user').delete({ where: { id }, populate: ['roles'] });
return strapi.query('admin::user').delete({ where: { id }, populate: ['roles'] });
};
/** Delete a user
@ -239,7 +237,7 @@ const deleteById = async id => {
const deleteByIds = async ids => {
// Check at least one super admin remains
const superAdminRole = await getService('role').getSuperAdminWithUsersCount();
const nbOfSuperAdminToDelete = await strapi.query('strapi::user').count({
const nbOfSuperAdminToDelete = await strapi.query('admin::user').count({
where: {
id: ids,
roles: { id: superAdminRole.id },
@ -255,7 +253,7 @@ const deleteByIds = async ids => {
const deletedUsers = [];
for (const id of ids) {
const deletedUser = await strapi.query('strapi::user').delete({
const deletedUser = await strapi.query('admin::user').delete({
where: { id },
populate: ['roles'],
});
@ -270,7 +268,7 @@ const deleteByIds = async ids => {
* @returns {Promise<number>}
*/
const countUsersWithoutRole = async () => {
return strapi.query('strapi::user').count({
return strapi.query('admin::user').count({
where: {
roles: {
id: { $null: true },
@ -285,14 +283,14 @@ const countUsersWithoutRole = async () => {
* @returns {Promise<number>}
*/
const count = async (where = {}) => {
return strapi.query('strapi::user').count({ where });
return strapi.query('admin::user').count({ where });
};
/** Assign some roles to several users
* @returns {undefined}
*/
const assignARoleToAll = async roleId => {
const users = await strapi.query('strapi::user').findMany({
const users = await strapi.query('admin::user').findMany({
select: ['id'],
where: {
roles: { id: { $null: true } },
@ -301,7 +299,7 @@ const assignARoleToAll = async roleId => {
await Promise.all(
users.map(user => {
return strapi.query('strapi::user').update({
return strapi.query('admin::user').update({
where: { id: user.id },
data: { roles: [roleId] },
});

View File

@ -28,7 +28,7 @@ const findCreatorRoles = entity => {
if (has(createdByPath, entity)) {
const creatorId = prop(createdByPath, entity);
return strapi.query('strapi::role').findMany({ where: { users: { id: creatorId } } });
return strapi.query('admin::role').findMany({ where: { users: { id: creatorId } } });
}
return [];

View File

@ -36,7 +36,7 @@ const VALID_UID_TARGETS = ['string', 'text'];
const FORBIDDEN_ATTRIBUTE_NAMES = ['__component', '__contentType'];
const PREFIX = 'strapi::';
const STRAPI_USER = 'strapi::user';
const STRAPI_USER = 'admin::user';
const UPLOAD_FILE = 'plugin::upload.file';
module.exports = {

View File

@ -85,15 +85,11 @@ class Strapi {
}
contentType(name) {
// TODO: expose a CT with a cleaner api to access attributes etc directly
return this.container.get('content-types').get(name).schema;
return this.container.get('content-types').get(name);
}
get contentTypes() {
// TODO: expose a CT with a cleaner api to access attributes etc directly
const cts = this.container.get('content-types').getAll();
return _.mapValues(cts, value => value.schema);
return this.container.get('content-types').getAll();
}
plugin(name) {
@ -233,7 +229,7 @@ class Strapi {
loadAdmin() {
this.admin = require('@strapi/admin/strapi-server');
strapi.container.get('content-types').add(`strapi::`, strapi.admin.contentTypes);
strapi.container.get('content-types').add(`admin::`, strapi.admin.contentTypes);
// TODO: rename into just admin and ./config/admin.js
const userAdminConfig = strapi.config.get('server.admin');

View File

@ -19,11 +19,11 @@ const createContentType = (uid, definition) => {
throw new Error(`Content Type Definition is invalid for ${uid}'.\n${e.errors}`);
}
const createdContentType = cloneDeep(definition);
const { schema, actions, lifecycles } = cloneDeep(definition);
// general info
Object.assign(createdContentType.schema, {
kind: createdContentType.schema.kind || 'collectionType',
Object.assign(schema, {
kind: schema.kind || 'collectionType',
__schema__: pickSchema(definition.schema),
modelType: 'contentType',
modelName: definition.schema.info.singularName,
@ -31,27 +31,26 @@ const createContentType = (uid, definition) => {
});
if (uid.startsWith('api::')) {
Object.assign(createdContentType.schema, {
Object.assign(schema, {
uid,
apiName: uid.split('::')[1].split('.')[0],
collectionName: definition.schema.collectionName || definition.schema.info.singularName,
globalId: getGlobalId(definition.schema, definition.schema.info.singularName),
collectionName: schema.collectionName || schema.info.singularName,
globalId: getGlobalId(schema, schema.info.singularName),
});
} else if (uid.startsWith('plugin::')) {
const pluginName = uid.split('::')[1].split('.')[0];
Object.assign(createdContentType.schema, {
Object.assign(schema, {
uid,
plugin: pluginName, // TODO: to be set in load-plugins.js
collectionName:
createdContentType.schema.collectionName ||
`${pluginName}_${definition.schema.info.singularName}`.toLowerCase(),
globalId: getGlobalId(definition.schema, definition.schema.info.singularName, pluginName),
schema.collectionName || `${pluginName}_${schema.info.singularName}`.toLowerCase(),
globalId: getGlobalId(schema, schema.info.singularName, pluginName),
});
} else if (uid.startsWith('strapi::')) {
Object.assign(createdContentType.schema, {
} else if (uid.startsWith('admin::')) {
Object.assign(schema, {
uid,
plugin: 'admin',
globalId: getGlobalId(definition.schema, definition.schema.info.singularName, 'admin'),
globalId: getGlobalId(schema, schema.info.singularName, 'admin'),
});
} else {
throw new Error(
@ -59,7 +58,7 @@ const createContentType = (uid, definition) => {
);
}
Object.defineProperty(createdContentType.schema, 'privateAttributes', {
Object.defineProperty(schema, 'privateAttributes', {
get() {
// FIXME: to fix
// return strapi.getModel(model.uid).privateAttributes;
@ -68,7 +67,7 @@ const createContentType = (uid, definition) => {
});
// attributes
Object.assign(createdContentType.schema.attributes, {
Object.assign(schema.attributes, {
[CREATED_AT_ATTRIBUTE]: {
type: 'datetime',
default: () => new Date(),
@ -80,8 +79,8 @@ const createContentType = (uid, definition) => {
},
});
if (hasDraftAndPublish(createdContentType.schema)) {
createdContentType.schema.attributes[PUBLISHED_AT_ATTRIBUTE] = {
if (hasDraftAndPublish(schema)) {
schema.attributes[PUBLISHED_AT_ATTRIBUTE] = {
type: 'datetime',
configurable: false,
writable: true,
@ -89,12 +88,12 @@ const createContentType = (uid, definition) => {
};
}
const isPrivate = !_.get(createdContentType.schema, 'options.populateCreatorFields', false);
const isPrivate = !_.get(schema, 'options.populateCreatorFields', false);
createdContentType.schema.attributes[CREATED_BY_ATTRIBUTE] = {
schema.attributes[CREATED_BY_ATTRIBUTE] = {
type: 'relation',
relation: 'oneToOne',
target: 'strapi::user',
target: 'admin::user',
configurable: false,
writable: false,
visible: false,
@ -102,10 +101,10 @@ const createContentType = (uid, definition) => {
private: isPrivate,
};
createdContentType.schema.attributes[UPDATED_BY_ATTRIBUTE] = {
schema.attributes[UPDATED_BY_ATTRIBUTE] = {
type: 'relation',
relation: 'oneToOne',
target: 'strapi::user',
target: 'admin::user',
configurable: false,
writable: false,
visible: false,
@ -113,7 +112,11 @@ const createContentType = (uid, definition) => {
private: isPrivate,
};
return createdContentType;
return {
...schema,
actions: actions,
lifecycles: lifecycles,
};
};
const getGlobalId = (model, modelName, prefix) => {

View File

@ -14,7 +14,7 @@ module.exports = async function isInitialized(strapi) {
}
// test if there is at least one admin
const anyAdministrator = await strapi.query('strapi::user').findOne({ select: ['id'] });
const anyAdministrator = await strapi.query('admin::user').findOne({ select: ['id'] });
return !isNil(anyAdministrator);
} catch (err) {

View File

@ -29,7 +29,7 @@ const findEntityAndCheckPermissions = async (ability, action, model, id) => {
const pm = strapi.admin.services.permission.createPermissionsManager({ ability, action, model });
const roles = _.has(entity, `${CREATED_BY_ATTRIBUTE}.id`)
? await strapi.query('strapi::role').findMany({
? await strapi.query('admin::role').findMany({
where: {
users: { id: entity[CREATED_BY_ATTRIBUTE].id },
},