node_modules ignore

This commit is contained in:
oier committed 2025-05-08 23:43:47 +02:00
1 parent e19d52f172
commit 4574544c9f
65041 files changed
+10593536

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
import { Logger } from '@strapi/logger';
import { Database } from '@strapi/database';
import type { Core, Modules, UID, Schema } from '@strapi/types';
import { Container } from './container';
import { FeaturesService } from './services/features';
declare class Strapi extends Container implements Core.Strapi {
app: any;
isLoaded: boolean;
internal_config: Record<string, unknown>;
constructor(opts: StrapiOptions);
get admin(): Core.Module;
get EE(): boolean;
get ee(): Core.Strapi['ee'];
get dirs(): Core.StrapiDirectories;
get reload(): Core.Reloader;
get db(): Database;
get requestContext(): Modules.RequestContext.RequestContext;
get customFields(): Modules.CustomFields.CustomFields;
get entityValidator(): Modules.EntityValidator.EntityValidator;
/**
* @deprecated `strapi.entityService` will be removed in the next major version
*/
get entityService(): Modules.EntityService.EntityService;
get documents(): Modules.Documents.Service;
get features(): FeaturesService;
get fetch(): Modules.Fetch.Fetch;
get cron(): Modules.Cron.CronService;
get log(): Logger;
get startupLogger(): Core.StartupLogger;
get eventHub(): Modules.EventHub.EventHub;
get fs(): Core.StrapiFS;
get server(): Modules.Server.Server;
get telemetry(): Modules.Metrics.TelemetryService;
get store(): Modules.CoreStore.CoreStore;
get config(): any;
get services(): any;
service(uid: UID.Service): any;
get controllers(): any;
controller(uid: UID.Controller): any;
get contentTypes(): Schema.ContentTypes;
contentType(name: UID.ContentType): any;
get components(): Schema.Components;
get policies(): any;
policy(name: string): any;
get middlewares(): any;
middleware(name: string): any;
get plugins(): Record<string, Core.Plugin>;
plugin(name: string): Core.Plugin;
get hooks(): any;
hook(name: string): any;
get apis(): any;
api(name: string): Core.Module;
get auth(): any;
get contentAPI(): any;
get sanitizers(): any;
get validators(): any;
start(): Promise<this>;
registerInternalServices(): void;
sendStartupTelemetry(): void;
openAdmin({ isInitialized }: {
isInitialized: boolean;
}): Promise<void>;
postListen(): Promise<void>;
/**
* Add behaviors to the server
*/
listen(): Promise<void>;
stopWithError(err: unknown, customMessage?: string): never;
stop(exitCode?: number): never;
load(): Promise<this>;
register(): Promise<this>;
bootstrap(): Promise<this>;
configureGlobalProxy(): void;
destroy(): Promise<void>;
runPluginsLifecycles(lifecycleName: 'register' | 'bootstrap' | 'destroy'): Promise<void>;
runUserLifecycles(lifecycleName: 'register' | 'bootstrap' | 'destroy'): Promise<void>;
getModel(uid: UID.ContentType): Schema.ContentType;
getModel(uid: UID.Component): Schema.Component;
/**
* @deprecated Use `strapi.db.query` instead
*/
query(uid: UID.Schema): import("@strapi/database/dist/entity-manager").Repository;
}
export interface StrapiOptions {
appDir: string;
distDir: string;
autoReload?: boolean;
serveAdminPanel?: boolean;
}
export default Strapi;
//# sourceMappingURL=Strapi.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Strapi.d.ts","sourceRoot":"","sources":["../src/Strapi.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAQhE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAgBxC,OAAO,EAAE,eAAe,EAAyB,MAAM,qBAAqB,CAAC;AAM7E,cAAM,MAAO,SAAQ,SAAU,YAAW,IAAI,CAAC,MAAM;IACnD,GAAG,EAAE,GAAG,CAAC;IAET,QAAQ,EAAE,OAAO,CAAS;IAE1B,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAM;gBAElC,IAAI,EAAE,aAAa;IAY/B,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,CAEvB;IAED,IAAI,EAAE,IAAI,OAAO,CAEhB;IAED,IAAI,EAAE,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAE1B;IAED,IAAI,IAAI,IAAI,IAAI,CAAC,iBAAiB,CAEjC;IAED,IAAI,MAAM,IAAI,IAAI,CAAC,QAAQ,CAE1B;IAED,IAAI,EAAE,IAAI,QAAQ,CAEjB;IAED,IAAI,cAAc,IAAI,OAAO,CAAC,cAAc,CAAC,cAAc,CAE1D;IAED,IAAI,YAAY,IAAI,OAAO,CAAC,YAAY,CAAC,YAAY,CAEpD;IAED,IAAI,eAAe,IAAI,OAAO,CAAC,eAAe,CAAC,eAAe,CAE7D;IAED;;OAEG;IACH,IAAI,aAAa,IAAI,OAAO,CAAC,aAAa,CAAC,aAAa,CAEvD;IAED,IAAI,SAAS,IAAI,OAAO,CAAC,SAAS,CAAC,OAAO,CAEzC;IAED,IAAI,QAAQ,IAAI,eAAe,CAE9B;IAED,IAAI,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,CAE/B;IAED,IAAI,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,WAAW,CAEnC;IAED,IAAI,GAAG,IAAI,MAAM,CAEhB;IAED,IAAI,aAAa,IAAI,IAAI,CAAC,aAAa,CAEtC;IAED,IAAI,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAExC;IAED,IAAI,EAAE,IAAI,IAAI,CAAC,QAAQ,CAEtB;IAED,IAAI,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,CAElC;IAED,IAAI,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,gBAAgB,CAEhD;IAED,IAAI,KAAK,IAAI,OAAO,CAAC,SAAS,CAAC,SAAS,CAEvC;IAED,IAAI,MAAM,QAET;IAED,IAAI,QAAQ,QAEX;IAED,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO;IAIxB,IAAI,WAAW,QAEd;IAED,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,UAAU;IAI9B,IAAI,YAAY,IAAI,MAAM,CAAC,YAAY,CAEtC;IAED,WAAW,CAAC,IAAI,EAAE,GAAG,CAAC,WAAW;IAIjC,IAAI,UAAU,IAAI,MAAM,CAAC,UAAU,CAElC;IAED,IAAI,QAAQ,QAEX;IAED,MAAM,CAAC,IAAI,EAAE,MAAM;IAInB,IAAI,WAAW,QAEd;IAED,UAAU,CAAC,IAAI,EAAE,MAAM;IAIvB,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAEzC;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM;IAIjC,IAAI,KAAK,QAER;IAED,IAAI,CAAC,IAAI,EAAE,MAAM;IAIjB,IAAI,IAAI,QAEP;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM;IAI9B,IAAI,IAAI,QAEP;IAED,IAAI,UAAU,QAEb;IAED,IAAI,UAAU,QAEb;IAED,IAAI,UAAU,QAEb;IAEK,KAAK;IAeX,wBAAwB;IA6CxB,oBAAoB;IAwBd,SAAS,CAAC,EAAE,aAAa,EAAE,EAAE;QAAE,aAAa,EAAE,OAAO,CAAA;KAAE;IAevD,UAAU;IAUhB;;OAEG;IACG,MAAM;IAwBZ,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,KAAK;IAU1D,IAAI,CAAC,QAAQ,SAAI,GAAG,KAAK;IAWnB,IAAI;IASJ,QAAQ;IAiBR,SAAS;IAkEf,oBAAoB;IAsBd,OAAO;IAwBP,oBAAoB,CAAC,aAAa,EAAE,UAAU,GAAG,WAAW,GAAG,SAAS;IAKxE,iBAAiB,CAAC,aAAa,EAAE,UAAU,GAAG,WAAW,GAAG,SAAS;IAQ3E,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW;IAClD,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS;IAW9C;;OAEG;IACH,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM;CAGtB;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,eAAe,MAAM,CAAC"}
+455
View File
@@ -0,0 +1,455 @@
'use strict';
var globalAgent = require('global-agent');
var path = require('path');
var _ = require('lodash');
var fp = require('lodash/fp');
var logger = require('@strapi/logger');
var database = require('@strapi/database');
var tsUtils = require('@strapi/typescript-utils');
var index$8 = require('./configuration/index.js');
var factories = require('./factories.js');
var openBrowser = require('./utils/open-browser.js');
var isInitialized = require('./utils/is-initialized.js');
var index = require('./ee/index.js');
require('package-json');
require('configstore');
require('semver');
require('boxen');
require('chalk');
require('@strapi/utils');
var fetch = require('./utils/fetch.js');
var convertCustomFieldType = require('./utils/convert-custom-field-type.js');
var startupLogger = require('./utils/startup-logger.js');
var transformContentTypesToModels = require('./utils/transform-content-types-to-models.js');
var lifecycles = require('./utils/lifecycles.js');
require('node:path');
var container = require('./container.js');
var fs = require('./services/fs.js');
var eventHub = require('./services/event-hub.js');
var index$3 = require('./services/server/index.js');
var reloader = require('./services/reloader.js');
var index$7 = require('./providers/index.js');
var index$5 = require('./services/entity-service/index.js');
var queryParams = require('./services/query-params.js');
var index$4 = require('./services/entity-validator/index.js');
var requestContext = require('./services/request-context.js');
var index$2 = require('./services/auth/index.js');
var customFields = require('./services/custom-fields.js');
var index$1 = require('./services/content-api/index.js');
var dynamicZones = require('./services/utils/dynamic-zones.js');
var features = require('./services/features.js');
var index$6 = require('./services/document-service/index.js');
var coreStore = require('./services/core-store.js');
var config = require('./services/config.js');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var globalAgent__namespace = /*#__PURE__*/_interopNamespaceDefault(globalAgent);
class Strapi extends container.Container {
get admin() {
return this.get('admin');
}
get EE() {
return index.isEE;
}
get ee() {
return index;
}
get dirs() {
return this.config.get('dirs');
}
get reload() {
return this.get('reload');
}
get db() {
return this.get('db');
}
get requestContext() {
return this.get('requestContext');
}
get customFields() {
return this.get('customFields');
}
get entityValidator() {
return this.get('entityValidator');
}
/**
* @deprecated `strapi.entityService` will be removed in the next major version
*/ get entityService() {
return this.get('entityService');
}
get documents() {
return this.get('documents');
}
get features() {
return this.get('features');
}
get fetch() {
return this.get('fetch');
}
get cron() {
return this.get('cron');
}
get log() {
return this.get('logger');
}
get startupLogger() {
return this.get('startupLogger');
}
get eventHub() {
return this.get('eventHub');
}
get fs() {
return this.get('fs');
}
get server() {
return this.get('server');
}
get telemetry() {
return this.get('telemetry');
}
get store() {
return this.get('coreStore');
}
get config() {
return this.get('config');
}
get services() {
return this.get('services').getAll();
}
service(uid) {
return this.get('services').get(uid);
}
get controllers() {
return this.get('controllers').getAll();
}
controller(uid) {
return this.get('controllers').get(uid);
}
get contentTypes() {
return this.get('content-types').getAll();
}
contentType(name) {
return this.get('content-types').get(name);
}
get components() {
return this.get('components').getAll();
}
get policies() {
return this.get('policies').getAll();
}
policy(name) {
return this.get('policies').get(name);
}
get middlewares() {
return this.get('middlewares').getAll();
}
middleware(name) {
return this.get('middlewares').get(name);
}
get plugins() {
return this.get('plugins').getAll();
}
plugin(name) {
return this.get('plugins').get(name);
}
get hooks() {
return this.get('hooks').getAll();
}
hook(name) {
return this.get('hooks').get(name);
}
get apis() {
return this.get('apis').getAll();
}
api(name) {
return this.get('apis').get(name);
}
get auth() {
return this.get('auth');
}
get contentAPI() {
return this.get('content-api');
}
get sanitizers() {
return this.get('sanitizers');
}
get validators() {
return this.get('validators');
}
async start() {
try {
if (!this.isLoaded) {
await this.load();
}
await this.listen();
return this;
} catch (error) {
return this.stopWithError(error);
}
}
// TODO: split into more providers
registerInternalServices() {
const config$1 = config.createConfigProvider(this.internal_config, this);
const logger$1 = logger.createLogger({
level: 'http',
...config$1.get('logger'),
...config$1.get('server.logger.config')
});
// Instantiate the Strapi container
this.add('config', ()=>config$1).add('query-params', queryParams(this)).add('content-api', index$1(this)).add('auth', index$2()).add('server', ()=>index$3.createServer(this)).add('fs', ()=>fs(this)).add('eventHub', ()=>eventHub()).add('startupLogger', ()=>startupLogger.createStartupLogger(this)).add('logger', ()=>logger$1).add('fetch', ()=>fetch.createStrapiFetch(this)).add('features', ()=>features.createFeaturesService(this)).add('requestContext', requestContext).add('customFields', customFields(this)).add('entityValidator', index$4).add('entityService', ()=>index$5({
strapi: this,
db: this.db
})).add('documents', ()=>index$6.createDocumentService(this)).add('db', ()=>{
const tsDir = tsUtils.resolveOutDirSync(this.dirs.app.root);
const tsMigrationsEnabled = this.config.get('database.settings.useTypescriptMigrations') === true && tsDir;
const projectDir = tsMigrationsEnabled ? tsDir : this.dirs.app.root;
return new database.Database(_.merge(this.config.get('database'), {
logger: logger$1,
settings: {
migrations: {
dir: path.join(projectDir, 'database/migrations')
}
}
}));
}).add('reload', ()=>reloader.createReloader(this));
}
sendStartupTelemetry() {
// Emit started event.
// do not await to avoid slower startup
// This event is anonymous
this.telemetry.send('didStartServer', {
groupProperties: {
database: this.config.get('database.connection.client'),
plugins: Object.keys(this.plugins),
numberOfAllContentTypes: _.size(this.contentTypes),
numberOfComponents: _.size(this.components),
numberOfDynamicZones: dynamicZones(),
numberOfCustomControllers: Object.values(this.controllers).filter(// TODO: Fix this at the content API loader level to prevent future types issues
(controller)=>controller !== undefined && factories.isCustomController(controller)).length,
environment: this.config.environment
}
}).catch(this.log.error);
}
async openAdmin({ isInitialized }) {
const shouldOpenAdmin = this.config.get('environment') === 'development' && this.config.get('admin.autoOpen', true) !== false;
if (shouldOpenAdmin && !isInitialized) {
try {
await openBrowser.openBrowser(this.config);
this.telemetry.send('didOpenTab');
} catch (e) {
this.telemetry.send('didNotOpenTab');
}
}
}
async postListen() {
const isInitialized$1 = await isInitialized.isInitialized(this);
this.startupLogger.logStartupMessage({
isInitialized: isInitialized$1
});
this.log.info('Strapi started successfully');
this.sendStartupTelemetry();
this.openAdmin({
isInitialized: isInitialized$1
});
}
/**
* Add behaviors to the server
*/ async listen() {
return new Promise((resolve, reject)=>{
const onListen = async ()=>{
try {
await this.postListen();
resolve();
} catch (error) {
reject(error);
}
};
const listenSocket = this.config.get('server.socket');
if (listenSocket) {
this.server.listen(listenSocket, onListen);
} else {
const { host, port } = this.config.get('server');
this.server.listen(port, host, onListen);
}
});
}
stopWithError(err, customMessage) {
this.log.debug(`⛔️ Server wasn't able to start properly.`);
if (customMessage) {
this.log.error(customMessage);
}
this.log.error(err);
return this.stop();
}
stop(exitCode = 1) {
this.destroy();
if (this.config.get('autoReload')) {
process.send?.('stop');
}
// Kill process
process.exit(exitCode);
}
async load() {
await this.register();
await this.bootstrap();
this.isLoaded = true;
return this;
}
async register() {
// @ts-expect-error: init is internal
this.ee.init(this.dirs.app.root, this.log);
for (const provider of index$7.providers){
await provider.register?.(this);
}
await this.runPluginsLifecycles(lifecycles.LIFECYCLES.REGISTER);
await this.runUserLifecycles(lifecycles.LIFECYCLES.REGISTER);
// NOTE: Swap type customField for underlying data type
convertCustomFieldType.convertCustomFieldType(this);
return this;
}
async bootstrap() {
this.configureGlobalProxy();
const models = [
...transformContentTypesToModels.transformContentTypesToModels([
...Object.values(this.contentTypes),
...Object.values(this.components)
], this.db.metadata.identifiers),
...this.get('models').get()
];
await this.db.init({
models
});
let oldContentTypes;
if (await this.db.getSchemaConnection().hasTable(coreStore.coreStoreModel.tableName)) {
oldContentTypes = await this.store.get({
type: 'strapi',
name: 'content_types',
key: 'schema'
});
}
await this.hook('strapi::content-types.beforeSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
const status = await this.db.schema.sync();
// if schemas have changed, run repairs
if (status === 'CHANGED') {
await this.db.repair.removeOrphanMorphType({
pivot: 'component_type'
});
}
if (this.EE) {
await index.checkLicense({
strapi: this
});
}
await this.hook('strapi::content-types.afterSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
await this.store.set({
type: 'strapi',
name: 'content_types',
key: 'schema',
value: this.contentTypes
});
await this.server.initMiddlewares();
this.server.initRouting();
await this.contentAPI.permissions.registerActions();
await this.runPluginsLifecycles(lifecycles.LIFECYCLES.BOOTSTRAP);
for (const provider of index$7.providers){
await provider.bootstrap?.(this);
}
await this.runUserLifecycles(lifecycles.LIFECYCLES.BOOTSTRAP);
return this;
}
configureGlobalProxy() {
const globalProxy = this.config.get('server.proxy.global');
const httpProxy = this.config.get('server.proxy.http') || globalProxy;
const httpsProxy = this.config.get('server.proxy.https') || globalProxy;
if (!httpProxy && !httpsProxy) {
return;
}
globalAgent__namespace.bootstrap();
if (httpProxy) {
this.log.info(`Using HTTP proxy: ${httpProxy}`);
global.GLOBAL_AGENT.HTTP_PROXY = httpProxy;
}
if (httpsProxy) {
this.log.info(`Using HTTPS proxy: ${httpsProxy}`);
global.GLOBAL_AGENT.HTTPS_PROXY = httpsProxy;
}
}
async destroy() {
this.log.info('Shutting down Strapi');
await this.runPluginsLifecycles(lifecycles.LIFECYCLES.DESTROY);
for (const provider of index$7.providers){
await provider.destroy?.(this);
}
await this.runUserLifecycles(lifecycles.LIFECYCLES.DESTROY);
await this.server.destroy();
this.eventHub.destroy();
await this.db?.destroy();
process.removeAllListeners();
// @ts-expect-error: Allow clean delete of global.strapi to allow re-instanciation
delete global.strapi;
this.log.info('Strapi has been shut down');
}
async runPluginsLifecycles(lifecycleName) {
// plugins
await this.get('modules')[lifecycleName]();
}
async runUserLifecycles(lifecycleName) {
// user
const userLifecycleFunction = this.app && this.app[lifecycleName];
if (fp.isFunction(userLifecycleFunction)) {
await userLifecycleFunction({
strapi: this
});
}
}
getModel(uid) {
if (uid in this.contentTypes) {
return this.contentTypes[uid];
}
if (uid in this.components) {
return this.components[uid];
}
}
/**
* @deprecated Use `strapi.db.query` instead
*/ query(uid) {
return this.db.query(uid);
}
constructor(opts){
super();
this.isLoaded = false;
this.internal_config = {};
this.internal_config = index$8.loadConfiguration(opts);
this.registerInternalServices();
for (const provider of index$7.providers){
provider.init?.(this);
}
}
}
module.exports = Strapi;
//# sourceMappingURL=Strapi.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Strapi.js","sources":["../src/Strapi.ts"],"sourcesContent":["import * as globalAgent from 'global-agent';\nimport path from 'path';\nimport _ from 'lodash';\nimport { isFunction } from 'lodash/fp';\nimport { Logger, createLogger } from '@strapi/logger';\nimport { Database } from '@strapi/database';\n\nimport type { Core, Modules, UID, Schema } from '@strapi/types';\n\nimport tsUtils from '@strapi/typescript-utils';\nimport { loadConfiguration } from './configuration';\n\nimport * as factories from './factories';\n\nimport * as utils from './utils';\nimport { Container } from './container';\nimport createStrapiFs from './services/fs';\nimport createEventHub from './services/event-hub';\nimport { createServer } from './services/server';\nimport { createReloader } from './services/reloader';\n\nimport { providers } from './providers';\nimport createEntityService from './services/entity-service';\nimport createQueryParamService from './services/query-params';\n\nimport entityValidator from './services/entity-validator';\nimport requestContext from './services/request-context';\nimport createAuth from './services/auth';\nimport createCustomFields from './services/custom-fields';\nimport createContentAPI from './services/content-api';\nimport getNumberOfDynamicZones from './services/utils/dynamic-zones';\nimport { FeaturesService, createFeaturesService } from './services/features';\nimport { createDocumentService } from './services/document-service';\n\nimport { coreStoreModel } from './services/core-store';\nimport { createConfigProvider } from './services/config';\n\nclass Strapi extends Container implements Core.Strapi {\n app: any;\n\n isLoaded: boolean = false;\n\n internal_config: Record<string, unknown> = {};\n\n constructor(opts: StrapiOptions) {\n super();\n\n this.internal_config = loadConfiguration(opts);\n\n this.registerInternalServices();\n\n for (const provider of providers) {\n provider.init?.(this);\n }\n }\n\n get admin(): Core.Module {\n return this.get('admin');\n }\n\n get EE(): boolean {\n return utils.ee.isEE;\n }\n\n get ee(): Core.Strapi['ee'] {\n return utils.ee;\n }\n\n get dirs(): Core.StrapiDirectories {\n return this.config.get('dirs');\n }\n\n get reload(): Core.Reloader {\n return this.get('reload');\n }\n\n get db(): Database {\n return this.get('db');\n }\n\n get requestContext(): Modules.RequestContext.RequestContext {\n return this.get('requestContext');\n }\n\n get customFields(): Modules.CustomFields.CustomFields {\n return this.get('customFields');\n }\n\n get entityValidator(): Modules.EntityValidator.EntityValidator {\n return this.get('entityValidator');\n }\n\n /**\n * @deprecated `strapi.entityService` will be removed in the next major version\n */\n get entityService(): Modules.EntityService.EntityService {\n return this.get('entityService');\n }\n\n get documents(): Modules.Documents.Service {\n return this.get('documents');\n }\n\n get features(): FeaturesService {\n return this.get('features');\n }\n\n get fetch(): Modules.Fetch.Fetch {\n return this.get('fetch');\n }\n\n get cron(): Modules.Cron.CronService {\n return this.get('cron');\n }\n\n get log(): Logger {\n return this.get('logger');\n }\n\n get startupLogger(): Core.StartupLogger {\n return this.get('startupLogger');\n }\n\n get eventHub(): Modules.EventHub.EventHub {\n return this.get('eventHub');\n }\n\n get fs(): Core.StrapiFS {\n return this.get('fs');\n }\n\n get server(): Modules.Server.Server {\n return this.get('server');\n }\n\n get telemetry(): Modules.Metrics.TelemetryService {\n return this.get('telemetry');\n }\n\n get store(): Modules.CoreStore.CoreStore {\n return this.get('coreStore');\n }\n\n get config() {\n return this.get('config');\n }\n\n get services() {\n return this.get('services').getAll();\n }\n\n service(uid: UID.Service) {\n return this.get('services').get(uid);\n }\n\n get controllers() {\n return this.get('controllers').getAll();\n }\n\n controller(uid: UID.Controller) {\n return this.get('controllers').get(uid);\n }\n\n get contentTypes(): Schema.ContentTypes {\n return this.get('content-types').getAll();\n }\n\n contentType(name: UID.ContentType) {\n return this.get('content-types').get(name);\n }\n\n get components(): Schema.Components {\n return this.get('components').getAll();\n }\n\n get policies() {\n return this.get('policies').getAll();\n }\n\n policy(name: string) {\n return this.get('policies').get(name);\n }\n\n get middlewares() {\n return this.get('middlewares').getAll();\n }\n\n middleware(name: string) {\n return this.get('middlewares').get(name);\n }\n\n get plugins(): Record<string, Core.Plugin> {\n return this.get('plugins').getAll();\n }\n\n plugin(name: string): Core.Plugin {\n return this.get('plugins').get(name);\n }\n\n get hookLine truncated
+434
View File
@@ -0,0 +1,434 @@
import * as globalAgent from 'global-agent';
import path from 'path';
import _ from 'lodash';
import { isFunction } from 'lodash/fp';
import { createLogger } from '@strapi/logger';
import { Database } from '@strapi/database';
import tsUtils from '@strapi/typescript-utils';
import { loadConfiguration } from './configuration/index.mjs';
import { isCustomController } from './factories.mjs';
import { openBrowser } from './utils/open-browser.mjs';
import { isInitialized } from './utils/is-initialized.mjs';
import index from './ee/index.mjs';
import 'package-json';
import 'configstore';
import 'semver';
import 'boxen';
import 'chalk';
import '@strapi/utils';
import { createStrapiFetch } from './utils/fetch.mjs';
import { convertCustomFieldType } from './utils/convert-custom-field-type.mjs';
import { createStartupLogger } from './utils/startup-logger.mjs';
import { transformContentTypesToModels } from './utils/transform-content-types-to-models.mjs';
import { LIFECYCLES } from './utils/lifecycles.mjs';
import 'node:path';
import { Container } from './container.mjs';
import createStrapiFs from './services/fs.mjs';
import createEventHub from './services/event-hub.mjs';
import { createServer } from './services/server/index.mjs';
import { createReloader } from './services/reloader.mjs';
import { providers } from './providers/index.mjs';
import createEntityService from './services/entity-service/index.mjs';
import createQueryParamService from './services/query-params.mjs';
import entityValidator from './services/entity-validator/index.mjs';
import requestCtx from './services/request-context.mjs';
import createAuthentication from './services/auth/index.mjs';
import createCustomFields from './services/custom-fields.mjs';
import createContentAPI from './services/content-api/index.mjs';
import getNumberOfDynamicZones from './services/utils/dynamic-zones.mjs';
import { createFeaturesService } from './services/features.mjs';
import { createDocumentService } from './services/document-service/index.mjs';
import { coreStoreModel } from './services/core-store.mjs';
import { createConfigProvider } from './services/config.mjs';
class Strapi extends Container {
get admin() {
return this.get('admin');
}
get EE() {
return index.isEE;
}
get ee() {
return index;
}
get dirs() {
return this.config.get('dirs');
}
get reload() {
return this.get('reload');
}
get db() {
return this.get('db');
}
get requestContext() {
return this.get('requestContext');
}
get customFields() {
return this.get('customFields');
}
get entityValidator() {
return this.get('entityValidator');
}
/**
* @deprecated `strapi.entityService` will be removed in the next major version
*/ get entityService() {
return this.get('entityService');
}
get documents() {
return this.get('documents');
}
get features() {
return this.get('features');
}
get fetch() {
return this.get('fetch');
}
get cron() {
return this.get('cron');
}
get log() {
return this.get('logger');
}
get startupLogger() {
return this.get('startupLogger');
}
get eventHub() {
return this.get('eventHub');
}
get fs() {
return this.get('fs');
}
get server() {
return this.get('server');
}
get telemetry() {
return this.get('telemetry');
}
get store() {
return this.get('coreStore');
}
get config() {
return this.get('config');
}
get services() {
return this.get('services').getAll();
}
service(uid) {
return this.get('services').get(uid);
}
get controllers() {
return this.get('controllers').getAll();
}
controller(uid) {
return this.get('controllers').get(uid);
}
get contentTypes() {
return this.get('content-types').getAll();
}
contentType(name) {
return this.get('content-types').get(name);
}
get components() {
return this.get('components').getAll();
}
get policies() {
return this.get('policies').getAll();
}
policy(name) {
return this.get('policies').get(name);
}
get middlewares() {
return this.get('middlewares').getAll();
}
middleware(name) {
return this.get('middlewares').get(name);
}
get plugins() {
return this.get('plugins').getAll();
}
plugin(name) {
return this.get('plugins').get(name);
}
get hooks() {
return this.get('hooks').getAll();
}
hook(name) {
return this.get('hooks').get(name);
}
get apis() {
return this.get('apis').getAll();
}
api(name) {
return this.get('apis').get(name);
}
get auth() {
return this.get('auth');
}
get contentAPI() {
return this.get('content-api');
}
get sanitizers() {
return this.get('sanitizers');
}
get validators() {
return this.get('validators');
}
async start() {
try {
if (!this.isLoaded) {
await this.load();
}
await this.listen();
return this;
} catch (error) {
return this.stopWithError(error);
}
}
// TODO: split into more providers
registerInternalServices() {
const config = createConfigProvider(this.internal_config, this);
const logger = createLogger({
level: 'http',
...config.get('logger'),
...config.get('server.logger.config')
});
// Instantiate the Strapi container
this.add('config', ()=>config).add('query-params', createQueryParamService(this)).add('content-api', createContentAPI(this)).add('auth', createAuthentication()).add('server', ()=>createServer(this)).add('fs', ()=>createStrapiFs(this)).add('eventHub', ()=>createEventHub()).add('startupLogger', ()=>createStartupLogger(this)).add('logger', ()=>logger).add('fetch', ()=>createStrapiFetch(this)).add('features', ()=>createFeaturesService(this)).add('requestContext', requestCtx).add('customFields', createCustomFields(this)).add('entityValidator', entityValidator).add('entityService', ()=>createEntityService({
strapi: this,
db: this.db
})).add('documents', ()=>createDocumentService(this)).add('db', ()=>{
const tsDir = tsUtils.resolveOutDirSync(this.dirs.app.root);
const tsMigrationsEnabled = this.config.get('database.settings.useTypescriptMigrations') === true && tsDir;
const projectDir = tsMigrationsEnabled ? tsDir : this.dirs.app.root;
return new Database(_.merge(this.config.get('database'), {
logger,
settings: {
migrations: {
dir: path.join(projectDir, 'database/migrations')
}
}
}));
}).add('reload', ()=>createReloader(this));
}
sendStartupTelemetry() {
// Emit started event.
// do not await to avoid slower startup
// This event is anonymous
this.telemetry.send('didStartServer', {
groupProperties: {
database: this.config.get('database.connection.client'),
plugins: Object.keys(this.plugins),
numberOfAllContentTypes: _.size(this.contentTypes),
numberOfComponents: _.size(this.components),
numberOfDynamicZones: getNumberOfDynamicZones(),
numberOfCustomControllers: Object.values(this.controllers).filter(// TODO: Fix this at the content API loader level to prevent future types issues
(controller)=>controller !== undefined && isCustomController(controller)).length,
environment: this.config.environment
}
}).catch(this.log.error);
}
async openAdmin({ isInitialized }) {
const shouldOpenAdmin = this.config.get('environment') === 'development' && this.config.get('admin.autoOpen', true) !== false;
if (shouldOpenAdmin && !isInitialized) {
try {
await openBrowser(this.config);
this.telemetry.send('didOpenTab');
} catch (e) {
this.telemetry.send('didNotOpenTab');
}
}
}
async postListen() {
const isInitialized$1 = await isInitialized(this);
this.startupLogger.logStartupMessage({
isInitialized: isInitialized$1
});
this.log.info('Strapi started successfully');
this.sendStartupTelemetry();
this.openAdmin({
isInitialized: isInitialized$1
});
}
/**
* Add behaviors to the server
*/ async listen() {
return new Promise((resolve, reject)=>{
const onListen = async ()=>{
try {
await this.postListen();
resolve();
} catch (error) {
reject(error);
}
};
const listenSocket = this.config.get('server.socket');
if (listenSocket) {
this.server.listen(listenSocket, onListen);
} else {
const { host, port } = this.config.get('server');
this.server.listen(port, host, onListen);
}
});
}
stopWithError(err, customMessage) {
this.log.debug(`⛔️ Server wasn't able to start properly.`);
if (customMessage) {
this.log.error(customMessage);
}
this.log.error(err);
return this.stop();
}
stop(exitCode = 1) {
this.destroy();
if (this.config.get('autoReload')) {
process.send?.('stop');
}
// Kill process
process.exit(exitCode);
}
async load() {
await this.register();
await this.bootstrap();
this.isLoaded = true;
return this;
}
async register() {
// @ts-expect-error: init is internal
this.ee.init(this.dirs.app.root, this.log);
for (const provider of providers){
await provider.register?.(this);
}
await this.runPluginsLifecycles(LIFECYCLES.REGISTER);
await this.runUserLifecycles(LIFECYCLES.REGISTER);
// NOTE: Swap type customField for underlying data type
convertCustomFieldType(this);
return this;
}
async bootstrap() {
this.configureGlobalProxy();
const models = [
...transformContentTypesToModels([
...Object.values(this.contentTypes),
...Object.values(this.components)
], this.db.metadata.identifiers),
...this.get('models').get()
];
await this.db.init({
models
});
let oldContentTypes;
if (await this.db.getSchemaConnection().hasTable(coreStoreModel.tableName)) {
oldContentTypes = await this.store.get({
type: 'strapi',
name: 'content_types',
key: 'schema'
});
}
await this.hook('strapi::content-types.beforeSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
const status = await this.db.schema.sync();
// if schemas have changed, run repairs
if (status === 'CHANGED') {
await this.db.repair.removeOrphanMorphType({
pivot: 'component_type'
});
}
if (this.EE) {
await index.checkLicense({
strapi: this
});
}
await this.hook('strapi::content-types.afterSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
await this.store.set({
type: 'strapi',
name: 'content_types',
key: 'schema',
value: this.contentTypes
});
await this.server.initMiddlewares();
this.server.initRouting();
await this.contentAPI.permissions.registerActions();
await this.runPluginsLifecycles(LIFECYCLES.BOOTSTRAP);
for (const provider of providers){
await provider.bootstrap?.(this);
}
await this.runUserLifecycles(LIFECYCLES.BOOTSTRAP);
return this;
}
configureGlobalProxy() {
const globalProxy = this.config.get('server.proxy.global');
const httpProxy = this.config.get('server.proxy.http') || globalProxy;
const httpsProxy = this.config.get('server.proxy.https') || globalProxy;
if (!httpProxy && !httpsProxy) {
return;
}
globalAgent.bootstrap();
if (httpProxy) {
this.log.info(`Using HTTP proxy: ${httpProxy}`);
global.GLOBAL_AGENT.HTTP_PROXY = httpProxy;
}
if (httpsProxy) {
this.log.info(`Using HTTPS proxy: ${httpsProxy}`);
global.GLOBAL_AGENT.HTTPS_PROXY = httpsProxy;
}
}
async destroy() {
this.log.info('Shutting down Strapi');
await this.runPluginsLifecycles(LIFECYCLES.DESTROY);
for (const provider of providers){
await provider.destroy?.(this);
}
await this.runUserLifecycles(LIFECYCLES.DESTROY);
await this.server.destroy();
this.eventHub.destroy();
await this.db?.destroy();
process.removeAllListeners();
// @ts-expect-error: Allow clean delete of global.strapi to allow re-instanciation
delete global.strapi;
this.log.info('Strapi has been shut down');
}
async runPluginsLifecycles(lifecycleName) {
// plugins
await this.get('modules')[lifecycleName]();
}
async runUserLifecycles(lifecycleName) {
// user
const userLifecycleFunction = this.app && this.app[lifecycleName];
if (isFunction(userLifecycleFunction)) {
await userLifecycleFunction({
strapi: this
});
}
}
getModel(uid) {
if (uid in this.contentTypes) {
return this.contentTypes[uid];
}
if (uid in this.components) {
return this.components[uid];
}
}
/**
* @deprecated Use `strapi.db.query` instead
*/ query(uid) {
return this.db.query(uid);
}
constructor(opts){
super();
this.isLoaded = false;
this.internal_config = {};
this.internal_config = loadConfiguration(opts);
this.registerInternalServices();
for (const provider of providers){
provider.init?.(this);
}
}
}
export { Strapi as default };
//# sourceMappingURL=Strapi.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Strapi.mjs","sources":["../src/Strapi.ts"],"sourcesContent":["import * as globalAgent from 'global-agent';\nimport path from 'path';\nimport _ from 'lodash';\nimport { isFunction } from 'lodash/fp';\nimport { Logger, createLogger } from '@strapi/logger';\nimport { Database } from '@strapi/database';\n\nimport type { Core, Modules, UID, Schema } from '@strapi/types';\n\nimport tsUtils from '@strapi/typescript-utils';\nimport { loadConfiguration } from './configuration';\n\nimport * as factories from './factories';\n\nimport * as utils from './utils';\nimport { Container } from './container';\nimport createStrapiFs from './services/fs';\nimport createEventHub from './services/event-hub';\nimport { createServer } from './services/server';\nimport { createReloader } from './services/reloader';\n\nimport { providers } from './providers';\nimport createEntityService from './services/entity-service';\nimport createQueryParamService from './services/query-params';\n\nimport entityValidator from './services/entity-validator';\nimport requestContext from './services/request-context';\nimport createAuth from './services/auth';\nimport createCustomFields from './services/custom-fields';\nimport createContentAPI from './services/content-api';\nimport getNumberOfDynamicZones from './services/utils/dynamic-zones';\nimport { FeaturesService, createFeaturesService } from './services/features';\nimport { createDocumentService } from './services/document-service';\n\nimport { coreStoreModel } from './services/core-store';\nimport { createConfigProvider } from './services/config';\n\nclass Strapi extends Container implements Core.Strapi {\n app: any;\n\n isLoaded: boolean = false;\n\n internal_config: Record<string, unknown> = {};\n\n constructor(opts: StrapiOptions) {\n super();\n\n this.internal_config = loadConfiguration(opts);\n\n this.registerInternalServices();\n\n for (const provider of providers) {\n provider.init?.(this);\n }\n }\n\n get admin(): Core.Module {\n return this.get('admin');\n }\n\n get EE(): boolean {\n return utils.ee.isEE;\n }\n\n get ee(): Core.Strapi['ee'] {\n return utils.ee;\n }\n\n get dirs(): Core.StrapiDirectories {\n return this.config.get('dirs');\n }\n\n get reload(): Core.Reloader {\n return this.get('reload');\n }\n\n get db(): Database {\n return this.get('db');\n }\n\n get requestContext(): Modules.RequestContext.RequestContext {\n return this.get('requestContext');\n }\n\n get customFields(): Modules.CustomFields.CustomFields {\n return this.get('customFields');\n }\n\n get entityValidator(): Modules.EntityValidator.EntityValidator {\n return this.get('entityValidator');\n }\n\n /**\n * @deprecated `strapi.entityService` will be removed in the next major version\n */\n get entityService(): Modules.EntityService.EntityService {\n return this.get('entityService');\n }\n\n get documents(): Modules.Documents.Service {\n return this.get('documents');\n }\n\n get features(): FeaturesService {\n return this.get('features');\n }\n\n get fetch(): Modules.Fetch.Fetch {\n return this.get('fetch');\n }\n\n get cron(): Modules.Cron.CronService {\n return this.get('cron');\n }\n\n get log(): Logger {\n return this.get('logger');\n }\n\n get startupLogger(): Core.StartupLogger {\n return this.get('startupLogger');\n }\n\n get eventHub(): Modules.EventHub.EventHub {\n return this.get('eventHub');\n }\n\n get fs(): Core.StrapiFS {\n return this.get('fs');\n }\n\n get server(): Modules.Server.Server {\n return this.get('server');\n }\n\n get telemetry(): Modules.Metrics.TelemetryService {\n return this.get('telemetry');\n }\n\n get store(): Modules.CoreStore.CoreStore {\n return this.get('coreStore');\n }\n\n get config() {\n return this.get('config');\n }\n\n get services() {\n return this.get('services').getAll();\n }\n\n service(uid: UID.Service) {\n return this.get('services').get(uid);\n }\n\n get controllers() {\n return this.get('controllers').getAll();\n }\n\n controller(uid: UID.Controller) {\n return this.get('controllers').get(uid);\n }\n\n get contentTypes(): Schema.ContentTypes {\n return this.get('content-types').getAll();\n }\n\n contentType(name: UID.ContentType) {\n return this.get('content-types').get(name);\n }\n\n get components(): Schema.Components {\n return this.get('components').getAll();\n }\n\n get policies() {\n return this.get('policies').getAll();\n }\n\n policy(name: string) {\n return this.get('policies').get(name);\n }\n\n get middlewares() {\n return this.get('middlewares').getAll();\n }\n\n middleware(name: string) {\n return this.get('middlewares').get(name);\n }\n\n get plugins(): Record<string, Core.Plugin> {\n return this.get('plugins').getAll();\n }\n\n plugin(name: string): Core.Plugin {\n return this.get('plugins').get(name);\n }\n\n get hooLine truncated
+10
View File
@@ -0,0 +1,10 @@
interface Options {
appDir?: string;
ignoreDiagnostics?: boolean;
}
export default function compile(options?: Options): Promise<{
appDir: string;
distDir: any;
}>;
export {};
//# sourceMappingURL=compile.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAEA,UAAU,OAAO;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,wBAA8B,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO;;;GActD"}
+27
View File
@@ -0,0 +1,27 @@
'use strict';
var tsUtils = require('@strapi/typescript-utils');
async function compile(options) {
const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
const outDir = await tsUtils.resolveOutDir(appDir);
if (isTSProject) {
await tsUtils.compile(appDir, {
configOptions: {
options: {
incremental: true
},
ignoreDiagnostics
}
});
}
const distDir = isTSProject ? outDir : appDir;
return {
appDir,
distDir
};
}
module.exports = compile;
//# sourceMappingURL=compile.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"compile.js","sources":["../src/compile.ts"],"sourcesContent":["import tsUtils from '@strapi/typescript-utils';\n\ninterface Options {\n appDir?: string;\n ignoreDiagnostics?: boolean;\n}\n\nexport default async function compile(options?: Options) {\n const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};\n const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n const outDir = await tsUtils.resolveOutDir(appDir);\n\n if (isTSProject) {\n await tsUtils.compile(appDir, {\n configOptions: { options: { incremental: true }, ignoreDiagnostics },\n });\n }\n\n const distDir = isTSProject ? outDir : appDir;\n\n return { appDir, distDir };\n}\n"],"names":["compile","options","appDir","process","cwd","ignoreDiagnostics","isTSProject","tsUtils","isUsingTypeScript","outDir","resolveOutDir","configOptions","incremental","distDir"],"mappings":";;;;AAOe,eAAeA,QAAQC,OAAiB,EAAA;IACrD,MAAM,EAAEC,MAASC,GAAAA,OAAAA,CAAQC,GAAG,EAAE,EAAEC,iBAAAA,GAAoB,KAAK,EAAE,GAAGJ,OAAAA,IAAW,EAAC;AAC1E,IAAA,MAAMK,WAAc,GAAA,MAAMC,OAAQC,CAAAA,iBAAiB,CAACN,MAAAA,CAAAA;AACpD,IAAA,MAAMO,MAAS,GAAA,MAAMF,OAAQG,CAAAA,aAAa,CAACR,MAAAA,CAAAA;AAE3C,IAAA,IAAII,WAAa,EAAA;QACf,MAAMC,OAAAA,CAAQP,OAAO,CAACE,MAAQ,EAAA;YAC5BS,aAAe,EAAA;gBAAEV,OAAS,EAAA;oBAAEW,WAAa,EAAA;AAAK,iBAAA;AAAGP,gBAAAA;AAAkB;AACrE,SAAA,CAAA;AACF;IAEA,MAAMQ,OAAAA,GAAUP,cAAcG,MAASP,GAAAA,MAAAA;IAEvC,OAAO;AAAEA,QAAAA,MAAAA;AAAQW,QAAAA;AAAQ,KAAA;AAC3B;;;;"}
+25
View File
@@ -0,0 +1,25 @@
import tsUtils from '@strapi/typescript-utils';
async function compile(options) {
const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
const outDir = await tsUtils.resolveOutDir(appDir);
if (isTSProject) {
await tsUtils.compile(appDir, {
configOptions: {
options: {
incremental: true
},
ignoreDiagnostics
}
});
}
const distDir = isTSProject ? outDir : appDir;
return {
appDir,
distDir
};
}
export { compile as default };
//# sourceMappingURL=compile.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"compile.mjs","sources":["../src/compile.ts"],"sourcesContent":["import tsUtils from '@strapi/typescript-utils';\n\ninterface Options {\n appDir?: string;\n ignoreDiagnostics?: boolean;\n}\n\nexport default async function compile(options?: Options) {\n const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};\n const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n const outDir = await tsUtils.resolveOutDir(appDir);\n\n if (isTSProject) {\n await tsUtils.compile(appDir, {\n configOptions: { options: { incremental: true }, ignoreDiagnostics },\n });\n }\n\n const distDir = isTSProject ? outDir : appDir;\n\n return { appDir, distDir };\n}\n"],"names":["compile","options","appDir","process","cwd","ignoreDiagnostics","isTSProject","tsUtils","isUsingTypeScript","outDir","resolveOutDir","configOptions","incremental","distDir"],"mappings":";;AAOe,eAAeA,QAAQC,OAAiB,EAAA;IACrD,MAAM,EAAEC,MAASC,GAAAA,OAAAA,CAAQC,GAAG,EAAE,EAAEC,iBAAAA,GAAoB,KAAK,EAAE,GAAGJ,OAAAA,IAAW,EAAC;AAC1E,IAAA,MAAMK,WAAc,GAAA,MAAMC,OAAQC,CAAAA,iBAAiB,CAACN,MAAAA,CAAAA;AACpD,IAAA,MAAMO,MAAS,GAAA,MAAMF,OAAQG,CAAAA,aAAa,CAACR,MAAAA,CAAAA;AAE3C,IAAA,IAAII,WAAa,EAAA;QACf,MAAMC,OAAAA,CAAQP,OAAO,CAACE,MAAQ,EAAA;YAC5BS,aAAe,EAAA;gBAAEV,OAAS,EAAA;oBAAEW,WAAa,EAAA;AAAK,iBAAA;AAAGP,gBAAAA;AAAkB;AACrE,SAAA,CAAA;AACF;IAEA,MAAMQ,OAAAA,GAAUP,cAAcG,MAASP,GAAAA,MAAAA;IAEvC,OAAO;AAAEA,QAAAA,MAAAA;AAAQW,QAAAA;AAAQ,KAAA;AAC3B;;;;"}
@@ -0,0 +1,3 @@
declare const _default: (dir: string) => Record<string, unknown>;
export default _default;
//# sourceMappingURL=config-loader.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/configuration/config-loader.ts"],"names":[],"mappings":"8BA2DqB,MAAM;AAA3B,wBAoFE"}
+119
View File
@@ -0,0 +1,119 @@
'use strict';
var path = require('path');
var fs = require('fs');
var loadConfigFile = require('../utils/load-config-file.js');
const VALID_EXTENSIONS = [
'.js',
'.json'
];
// These filenames are restricted, but will also emit a warning that the filename is probably a mistake
const MISTAKEN_FILENAMES = {
middleware: 'middlewares',
plugin: 'plugins'
};
// the following are restricted to prevent conflicts with existing STRAPI_* env vars or root level config options
// must all be lowercase to match validator
const RESTRICTED_FILENAMES = [
// existing env vars
'uuid',
'hosting',
'license',
'enforce',
'disable',
'enable',
'telemetry',
// reserved for future internal use
'strapi',
'internal',
// root level config options
// TODO: it would be better to move these out of the root config and allow them to be loaded
'launchedAt',
'serveAdminPanel',
'autoReload',
'environment',
'packageJsonStrapi',
'info',
'autoReload',
'dirs',
// probably mistaken/typo filenames
...Object.keys(MISTAKEN_FILENAMES)
];
// Existing Strapi configuration files
const STRAPI_CONFIG_FILENAMES = [
'admin',
'server',
'api',
'database',
'middlewares',
'plugins',
'features'
];
// Note: we don't have access to strapi logger at this point so we can't use it
const logWarning = (message)=>{
console.warn(message);
};
var loadConfigDir = ((dir)=>{
if (!fs.existsSync(dir)) return {};
const allFiles = fs.readdirSync(dir, {
withFileTypes: true
});
const seenFilenames = new Set();
const configFiles = allFiles.reduce((acc, file)=>{
const baseName = path.basename(file.name, path.extname(file.name));
const baseNameLower = baseName.toLowerCase();
const extension = path.extname(file.name);
const extensionLower = extension.toLowerCase();
if (!file.isFile()) {
return acc;
}
if (!VALID_EXTENSIONS.includes(extensionLower)) {
logWarning(`Config file not loaded, extension must be one of ${VALID_EXTENSIONS.join(',')}): ${file.name}`);
return acc;
}
if (RESTRICTED_FILENAMES.includes(baseNameLower)) {
logWarning(`Config file not loaded, restricted filename: ${file.name}`);
// suggest the filename they probably meant
if (baseNameLower in MISTAKEN_FILENAMES) {
console.log(`Did you mean ${MISTAKEN_FILENAMES[baseNameLower]}]} ?`);
}
return acc;
}
// restricted names and Strapi configs are also restricted from being prefixes
const restrictedPrefix = [
...RESTRICTED_FILENAMES,
...STRAPI_CONFIG_FILENAMES
].find((restrictedName)=>restrictedName.startsWith(baseNameLower) && restrictedName !== baseNameLower);
if (restrictedPrefix) {
logWarning(`Config file not loaded, filename cannot start with ${restrictedPrefix}: ${file.name}`);
}
/**
* Note: If user config files contain non-alpha-numeric characters, we won't be able to auto-load env
* into them.
*
* For the initial feature, we will only load our internal configs, but later when we provide a method
* to define the shape of custom configs, we will need to warn that those filenames can't be loaded
* for technical limitations on env variable names
* */ // if (!/^[A-Za-z0-9]+$/.test(baseName)) {
// logWarning("Using a non-alphanumeric config file name prevents Strapi from auto-loading it from environment variables.")
// }
// filter filenames without case-insensitive uniqueness
if (seenFilenames.has(baseNameLower)) {
logWarning(`Config file not loaded, case-insensitive name matches other config file: ${file.name}`);
return acc;
}
seenFilenames.add(baseNameLower);
// If file passes all filters, add it to the accumulator
acc.push(file);
return acc;
}, []);
return configFiles.reduce((acc, file)=>{
const key = path.basename(file.name, path.extname(file.name));
acc[key] = loadConfigFile.loadConfigFile(path.resolve(dir, file.name));
return acc;
}, {});
});
module.exports = loadConfigDir;
//# sourceMappingURL=config-loader.js.map
@@ -0,0 +1 @@
{"version":3,"file":"config-loader.js","sources":["../../src/configuration/config-loader.ts"],"sourcesContent":["import path from 'path';\nimport fs from 'fs';\nimport { loadConfigFile } from '../utils/load-config-file';\n\nconst VALID_EXTENSIONS = ['.js', '.json'];\n\n// These filenames are restricted, but will also emit a warning that the filename is probably a mistake\nconst MISTAKEN_FILENAMES = {\n middleware: 'middlewares',\n plugin: 'plugins',\n};\n\n// the following are restricted to prevent conflicts with existing STRAPI_* env vars or root level config options\n// must all be lowercase to match validator\nconst RESTRICTED_FILENAMES = [\n // existing env vars\n 'uuid',\n 'hosting',\n 'license',\n 'enforce',\n 'disable',\n 'enable',\n 'telemetry',\n\n // reserved for future internal use\n 'strapi',\n 'internal',\n\n // root level config options\n // TODO: it would be better to move these out of the root config and allow them to be loaded\n 'launchedAt',\n 'serveAdminPanel',\n 'autoReload',\n 'environment',\n 'packageJsonStrapi',\n 'info',\n 'autoReload',\n 'dirs',\n\n // probably mistaken/typo filenames\n ...Object.keys(MISTAKEN_FILENAMES),\n];\n\n// Existing Strapi configuration files\nconst STRAPI_CONFIG_FILENAMES = [\n 'admin',\n 'server',\n 'api',\n 'database',\n 'middlewares',\n 'plugins',\n 'features',\n];\n\n// Note: we don't have access to strapi logger at this point so we can't use it\nconst logWarning = (message: string) => {\n console.warn(message);\n};\n\nexport default (dir: string) => {\n if (!fs.existsSync(dir)) return {};\n\n const allFiles = fs.readdirSync(dir, { withFileTypes: true });\n const seenFilenames = new Set<string>();\n const configFiles = allFiles.reduce((acc, file) => {\n const baseName = path.basename(file.name, path.extname(file.name));\n const baseNameLower = baseName.toLowerCase();\n const extension = path.extname(file.name);\n const extensionLower = extension.toLowerCase();\n\n if (!file.isFile()) {\n return acc;\n }\n\n if (!VALID_EXTENSIONS.includes(extensionLower)) {\n logWarning(\n `Config file not loaded, extension must be one of ${VALID_EXTENSIONS.join(',')}): ${\n file.name\n }`\n );\n return acc;\n }\n\n if (RESTRICTED_FILENAMES.includes(baseNameLower)) {\n logWarning(`Config file not loaded, restricted filename: ${file.name}`);\n\n // suggest the filename they probably meant\n if (baseNameLower in MISTAKEN_FILENAMES) {\n console.log(\n `Did you mean ${MISTAKEN_FILENAMES[baseNameLower as keyof typeof MISTAKEN_FILENAMES]}]} ?`\n );\n }\n\n return acc;\n }\n\n // restricted names and Strapi configs are also restricted from being prefixes\n const restrictedPrefix = [...RESTRICTED_FILENAMES, ...STRAPI_CONFIG_FILENAMES].find(\n (restrictedName) =>\n restrictedName.startsWith(baseNameLower) && restrictedName !== baseNameLower\n );\n if (restrictedPrefix) {\n logWarning(\n `Config file not loaded, filename cannot start with ${restrictedPrefix}: ${file.name}`\n );\n }\n\n /**\n * Note: If user config files contain non-alpha-numeric characters, we won't be able to auto-load env\n * into them.\n *\n * For the initial feature, we will only load our internal configs, but later when we provide a method\n * to define the shape of custom configs, we will need to warn that those filenames can't be loaded\n * for technical limitations on env variable names\n * */\n // if (!/^[A-Za-z0-9]+$/.test(baseName)) {\n // logWarning(\"Using a non-alphanumeric config file name prevents Strapi from auto-loading it from environment variables.\")\n // }\n\n // filter filenames without case-insensitive uniqueness\n if (seenFilenames.has(baseNameLower)) {\n logWarning(\n `Config file not loaded, case-insensitive name matches other config file: ${file.name}`\n );\n return acc;\n }\n seenFilenames.add(baseNameLower);\n\n // If file passes all filters, add it to the accumulator\n acc.push(file);\n return acc;\n }, [] as fs.Dirent[]);\n\n return configFiles.reduce(\n (acc, file) => {\n const key = path.basename(file.name, path.extname(file.name));\n\n acc[key] = loadConfigFile(path.resolve(dir, file.name));\n\n return acc;\n },\n {} as Record<string, unknown>\n );\n};\n"],"names":["VALID_EXTENSIONS","MISTAKEN_FILENAMES","middleware","plugin","RESTRICTED_FILENAMES","Object","keys","STRAPI_CONFIG_FILENAMES","logWarning","message","console","warn","dir","fs","existsSync","allFiles","readdirSync","withFileTypes","seenFilenames","Set","configFiles","reduce","acc","file","baseName","path","basename","name","extname","baseNameLower","toLowerCase","extension","extensionLower","isFile","includes","join","log","restrictedPrefix","find","restrictedName","startsWith","has","add","push","key","loaLine truncated
+117
View File
@@ -0,0 +1,117 @@
import path from 'path';
import fs from 'fs';
import { loadConfigFile } from '../utils/load-config-file.mjs';
const VALID_EXTENSIONS = [
'.js',
'.json'
];
// These filenames are restricted, but will also emit a warning that the filename is probably a mistake
const MISTAKEN_FILENAMES = {
middleware: 'middlewares',
plugin: 'plugins'
};
// the following are restricted to prevent conflicts with existing STRAPI_* env vars or root level config options
// must all be lowercase to match validator
const RESTRICTED_FILENAMES = [
// existing env vars
'uuid',
'hosting',
'license',
'enforce',
'disable',
'enable',
'telemetry',
// reserved for future internal use
'strapi',
'internal',
// root level config options
// TODO: it would be better to move these out of the root config and allow them to be loaded
'launchedAt',
'serveAdminPanel',
'autoReload',
'environment',
'packageJsonStrapi',
'info',
'autoReload',
'dirs',
// probably mistaken/typo filenames
...Object.keys(MISTAKEN_FILENAMES)
];
// Existing Strapi configuration files
const STRAPI_CONFIG_FILENAMES = [
'admin',
'server',
'api',
'database',
'middlewares',
'plugins',
'features'
];
// Note: we don't have access to strapi logger at this point so we can't use it
const logWarning = (message)=>{
console.warn(message);
};
var loadConfigDir = ((dir)=>{
if (!fs.existsSync(dir)) return {};
const allFiles = fs.readdirSync(dir, {
withFileTypes: true
});
const seenFilenames = new Set();
const configFiles = allFiles.reduce((acc, file)=>{
const baseName = path.basename(file.name, path.extname(file.name));
const baseNameLower = baseName.toLowerCase();
const extension = path.extname(file.name);
const extensionLower = extension.toLowerCase();
if (!file.isFile()) {
return acc;
}
if (!VALID_EXTENSIONS.includes(extensionLower)) {
logWarning(`Config file not loaded, extension must be one of ${VALID_EXTENSIONS.join(',')}): ${file.name}`);
return acc;
}
if (RESTRICTED_FILENAMES.includes(baseNameLower)) {
logWarning(`Config file not loaded, restricted filename: ${file.name}`);
// suggest the filename they probably meant
if (baseNameLower in MISTAKEN_FILENAMES) {
console.log(`Did you mean ${MISTAKEN_FILENAMES[baseNameLower]}]} ?`);
}
return acc;
}
// restricted names and Strapi configs are also restricted from being prefixes
const restrictedPrefix = [
...RESTRICTED_FILENAMES,
...STRAPI_CONFIG_FILENAMES
].find((restrictedName)=>restrictedName.startsWith(baseNameLower) && restrictedName !== baseNameLower);
if (restrictedPrefix) {
logWarning(`Config file not loaded, filename cannot start with ${restrictedPrefix}: ${file.name}`);
}
/**
* Note: If user config files contain non-alpha-numeric characters, we won't be able to auto-load env
* into them.
*
* For the initial feature, we will only load our internal configs, but later when we provide a method
* to define the shape of custom configs, we will need to warn that those filenames can't be loaded
* for technical limitations on env variable names
* */ // if (!/^[A-Za-z0-9]+$/.test(baseName)) {
// logWarning("Using a non-alphanumeric config file name prevents Strapi from auto-loading it from environment variables.")
// }
// filter filenames without case-insensitive uniqueness
if (seenFilenames.has(baseNameLower)) {
logWarning(`Config file not loaded, case-insensitive name matches other config file: ${file.name}`);
return acc;
}
seenFilenames.add(baseNameLower);
// If file passes all filters, add it to the accumulator
acc.push(file);
return acc;
}, []);
return configFiles.reduce((acc, file)=>{
const key = path.basename(file.name, path.extname(file.name));
acc[key] = loadConfigFile(path.resolve(dir, file.name));
return acc;
}, {});
});
export { loadConfigDir as default };
//# sourceMappingURL=config-loader.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"config-loader.mjs","sources":["../../src/configuration/config-loader.ts"],"sourcesContent":["import path from 'path';\nimport fs from 'fs';\nimport { loadConfigFile } from '../utils/load-config-file';\n\nconst VALID_EXTENSIONS = ['.js', '.json'];\n\n// These filenames are restricted, but will also emit a warning that the filename is probably a mistake\nconst MISTAKEN_FILENAMES = {\n middleware: 'middlewares',\n plugin: 'plugins',\n};\n\n// the following are restricted to prevent conflicts with existing STRAPI_* env vars or root level config options\n// must all be lowercase to match validator\nconst RESTRICTED_FILENAMES = [\n // existing env vars\n 'uuid',\n 'hosting',\n 'license',\n 'enforce',\n 'disable',\n 'enable',\n 'telemetry',\n\n // reserved for future internal use\n 'strapi',\n 'internal',\n\n // root level config options\n // TODO: it would be better to move these out of the root config and allow them to be loaded\n 'launchedAt',\n 'serveAdminPanel',\n 'autoReload',\n 'environment',\n 'packageJsonStrapi',\n 'info',\n 'autoReload',\n 'dirs',\n\n // probably mistaken/typo filenames\n ...Object.keys(MISTAKEN_FILENAMES),\n];\n\n// Existing Strapi configuration files\nconst STRAPI_CONFIG_FILENAMES = [\n 'admin',\n 'server',\n 'api',\n 'database',\n 'middlewares',\n 'plugins',\n 'features',\n];\n\n// Note: we don't have access to strapi logger at this point so we can't use it\nconst logWarning = (message: string) => {\n console.warn(message);\n};\n\nexport default (dir: string) => {\n if (!fs.existsSync(dir)) return {};\n\n const allFiles = fs.readdirSync(dir, { withFileTypes: true });\n const seenFilenames = new Set<string>();\n const configFiles = allFiles.reduce((acc, file) => {\n const baseName = path.basename(file.name, path.extname(file.name));\n const baseNameLower = baseName.toLowerCase();\n const extension = path.extname(file.name);\n const extensionLower = extension.toLowerCase();\n\n if (!file.isFile()) {\n return acc;\n }\n\n if (!VALID_EXTENSIONS.includes(extensionLower)) {\n logWarning(\n `Config file not loaded, extension must be one of ${VALID_EXTENSIONS.join(',')}): ${\n file.name\n }`\n );\n return acc;\n }\n\n if (RESTRICTED_FILENAMES.includes(baseNameLower)) {\n logWarning(`Config file not loaded, restricted filename: ${file.name}`);\n\n // suggest the filename they probably meant\n if (baseNameLower in MISTAKEN_FILENAMES) {\n console.log(\n `Did you mean ${MISTAKEN_FILENAMES[baseNameLower as keyof typeof MISTAKEN_FILENAMES]}]} ?`\n );\n }\n\n return acc;\n }\n\n // restricted names and Strapi configs are also restricted from being prefixes\n const restrictedPrefix = [...RESTRICTED_FILENAMES, ...STRAPI_CONFIG_FILENAMES].find(\n (restrictedName) =>\n restrictedName.startsWith(baseNameLower) && restrictedName !== baseNameLower\n );\n if (restrictedPrefix) {\n logWarning(\n `Config file not loaded, filename cannot start with ${restrictedPrefix}: ${file.name}`\n );\n }\n\n /**\n * Note: If user config files contain non-alpha-numeric characters, we won't be able to auto-load env\n * into them.\n *\n * For the initial feature, we will only load our internal configs, but later when we provide a method\n * to define the shape of custom configs, we will need to warn that those filenames can't be loaded\n * for technical limitations on env variable names\n * */\n // if (!/^[A-Za-z0-9]+$/.test(baseName)) {\n // logWarning(\"Using a non-alphanumeric config file name prevents Strapi from auto-loading it from environment variables.\")\n // }\n\n // filter filenames without case-insensitive uniqueness\n if (seenFilenames.has(baseNameLower)) {\n logWarning(\n `Config file not loaded, case-insensitive name matches other config file: ${file.name}`\n );\n return acc;\n }\n seenFilenames.add(baseNameLower);\n\n // If file passes all filters, add it to the accumulator\n acc.push(file);\n return acc;\n }, [] as fs.Dirent[]);\n\n return configFiles.reduce(\n (acc, file) => {\n const key = path.basename(file.name, path.extname(file.name));\n\n acc[key] = loadConfigFile(path.resolve(dir, file.name));\n\n return acc;\n },\n {} as Record<string, unknown>\n );\n};\n"],"names":["VALID_EXTENSIONS","MISTAKEN_FILENAMES","middleware","plugin","RESTRICTED_FILENAMES","Object","keys","STRAPI_CONFIG_FILENAMES","logWarning","message","console","warn","dir","fs","existsSync","allFiles","readdirSync","withFileTypes","seenFilenames","Set","configFiles","reduce","acc","file","baseName","path","basename","name","extname","baseNameLower","toLowerCase","extension","extensionLower","isFile","includes","join","log","restrictedPrefix","find","restrictedName","startsWith","has","add","push","key","loLine truncated
+10
View File
@@ -0,0 +1,10 @@
import type { Core } from '@strapi/types';
import type { StrapiOptions } from '../Strapi';
export type Options = {
app: string;
dist: string;
};
export declare const getDirs: ({ appDir, distDir }: StrapiOptions, config: {
server: Partial<Core.Config.Server>;
}) => Core.StrapiDirectories;
//# sourceMappingURL=get-dirs.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"get-dirs.d.ts","sourceRoot":"","sources":["../../src/configuration/get-dirs.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE/C,MAAM,MAAM,OAAO,GAAG;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,OAAO,wBACG,aAAa,UAC1B;IAAE,MAAM,EAAE,QAAQ,KAAK,MAAM,CAAC,MAAM,CAAC,CAAA;CAAE,KAC9C,KAAK,iBAwBN,CAAC"}
+33
View File
@@ -0,0 +1,33 @@
'use strict';
var path = require('path');
var fp = require('lodash/fp');
const getDirs = ({ appDir, distDir }, config)=>({
dist: {
root: distDir,
src: path.join(distDir, 'src'),
api: path.join(distDir, 'src', 'api'),
components: path.join(distDir, 'src', 'components'),
extensions: path.join(distDir, 'src', 'extensions'),
policies: path.join(distDir, 'src', 'policies'),
middlewares: path.join(distDir, 'src', 'middlewares'),
config: path.join(distDir, 'config')
},
app: {
root: appDir,
src: path.join(appDir, 'src'),
api: path.join(appDir, 'src', 'api'),
components: path.join(appDir, 'src', 'components'),
extensions: path.join(appDir, 'src', 'extensions'),
policies: path.join(appDir, 'src', 'policies'),
middlewares: path.join(appDir, 'src', 'middlewares'),
config: path.join(appDir, 'config')
},
static: {
public: path.resolve(appDir, fp.get('server.dirs.public', config))
}
});
exports.getDirs = getDirs;
//# sourceMappingURL=get-dirs.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"get-dirs.js","sources":["../../src/configuration/get-dirs.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { get } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\nimport type { StrapiOptions } from '../Strapi';\n\nexport type Options = {\n app: string;\n dist: string;\n};\n\nexport const getDirs = (\n { appDir, distDir }: StrapiOptions,\n config: { server: Partial<Core.Config.Server> }\n): Core.StrapiDirectories => ({\n dist: {\n root: distDir,\n src: join(distDir, 'src'),\n api: join(distDir, 'src', 'api'),\n components: join(distDir, 'src', 'components'),\n extensions: join(distDir, 'src', 'extensions'),\n policies: join(distDir, 'src', 'policies'),\n middlewares: join(distDir, 'src', 'middlewares'),\n config: join(distDir, 'config'),\n },\n app: {\n root: appDir,\n src: join(appDir, 'src'),\n api: join(appDir, 'src', 'api'),\n components: join(appDir, 'src', 'components'),\n extensions: join(appDir, 'src', 'extensions'),\n policies: join(appDir, 'src', 'policies'),\n middlewares: join(appDir, 'src', 'middlewares'),\n config: join(appDir, 'config'),\n },\n static: {\n public: resolve(appDir, get('server.dirs.public', config)),\n },\n});\n"],"names":["getDirs","appDir","distDir","config","dist","root","src","join","api","components","extensions","policies","middlewares","app","static","public","resolve","get"],"mappings":";;;;;AAWO,MAAMA,OAAU,GAAA,CACrB,EAAEC,MAAM,EAAEC,OAAO,EAAiB,EAClCC,MAAAA,IAC4B;QAC5BC,IAAM,EAAA;YACJC,IAAMH,EAAAA,OAAAA;AACNI,YAAAA,GAAAA,EAAKC,UAAKL,OAAS,EAAA,KAAA,CAAA;YACnBM,GAAKD,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,KAAA,CAAA;YAC1BO,UAAYF,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCQ,UAAYH,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCS,QAAUJ,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,UAAA,CAAA;YAC/BU,WAAaL,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,aAAA,CAAA;AAClCC,YAAAA,MAAAA,EAAQI,UAAKL,OAAS,EAAA,QAAA;AACxB,SAAA;QACAW,GAAK,EAAA;YACHR,IAAMJ,EAAAA,MAAAA;AACNK,YAAAA,GAAAA,EAAKC,UAAKN,MAAQ,EAAA,KAAA,CAAA;YAClBO,GAAKD,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,KAAA,CAAA;YACzBQ,UAAYF,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCS,UAAYH,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCU,QAAUJ,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,UAAA,CAAA;YAC9BW,WAAaL,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,aAAA,CAAA;AACjCE,YAAAA,MAAAA,EAAQI,UAAKN,MAAQ,EAAA,QAAA;AACvB,SAAA;QACAa,MAAQ,EAAA;YACNC,MAAQC,EAAAA,YAAAA,CAAQf,MAAQgB,EAAAA,MAAAA,CAAI,oBAAsBd,EAAAA,MAAAA,CAAAA;AACpD;AACF,KAAA;;;;"}
+31
View File
@@ -0,0 +1,31 @@
import { join, resolve } from 'path';
import { get } from 'lodash/fp';
const getDirs = ({ appDir, distDir }, config)=>({
dist: {
root: distDir,
src: join(distDir, 'src'),
api: join(distDir, 'src', 'api'),
components: join(distDir, 'src', 'components'),
extensions: join(distDir, 'src', 'extensions'),
policies: join(distDir, 'src', 'policies'),
middlewares: join(distDir, 'src', 'middlewares'),
config: join(distDir, 'config')
},
app: {
root: appDir,
src: join(appDir, 'src'),
api: join(appDir, 'src', 'api'),
components: join(appDir, 'src', 'components'),
extensions: join(appDir, 'src', 'extensions'),
policies: join(appDir, 'src', 'policies'),
middlewares: join(appDir, 'src', 'middlewares'),
config: join(appDir, 'config')
},
static: {
public: resolve(appDir, get('server.dirs.public', config))
}
});
export { getDirs };
//# sourceMappingURL=get-dirs.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"get-dirs.mjs","sources":["../../src/configuration/get-dirs.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { get } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\nimport type { StrapiOptions } from '../Strapi';\n\nexport type Options = {\n app: string;\n dist: string;\n};\n\nexport const getDirs = (\n { appDir, distDir }: StrapiOptions,\n config: { server: Partial<Core.Config.Server> }\n): Core.StrapiDirectories => ({\n dist: {\n root: distDir,\n src: join(distDir, 'src'),\n api: join(distDir, 'src', 'api'),\n components: join(distDir, 'src', 'components'),\n extensions: join(distDir, 'src', 'extensions'),\n policies: join(distDir, 'src', 'policies'),\n middlewares: join(distDir, 'src', 'middlewares'),\n config: join(distDir, 'config'),\n },\n app: {\n root: appDir,\n src: join(appDir, 'src'),\n api: join(appDir, 'src', 'api'),\n components: join(appDir, 'src', 'components'),\n extensions: join(appDir, 'src', 'extensions'),\n policies: join(appDir, 'src', 'policies'),\n middlewares: join(appDir, 'src', 'middlewares'),\n config: join(appDir, 'config'),\n },\n static: {\n public: resolve(appDir, get('server.dirs.public', config)),\n },\n});\n"],"names":["getDirs","appDir","distDir","config","dist","root","src","join","api","components","extensions","policies","middlewares","app","static","public","resolve","get"],"mappings":";;;AAWO,MAAMA,OAAU,GAAA,CACrB,EAAEC,MAAM,EAAEC,OAAO,EAAiB,EAClCC,MAAAA,IAC4B;QAC5BC,IAAM,EAAA;YACJC,IAAMH,EAAAA,OAAAA;AACNI,YAAAA,GAAAA,EAAKC,KAAKL,OAAS,EAAA,KAAA,CAAA;YACnBM,GAAKD,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,KAAA,CAAA;YAC1BO,UAAYF,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCQ,UAAYH,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCS,QAAUJ,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,UAAA,CAAA;YAC/BU,WAAaL,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,aAAA,CAAA;AAClCC,YAAAA,MAAAA,EAAQI,KAAKL,OAAS,EAAA,QAAA;AACxB,SAAA;QACAW,GAAK,EAAA;YACHR,IAAMJ,EAAAA,MAAAA;AACNK,YAAAA,GAAAA,EAAKC,KAAKN,MAAQ,EAAA,KAAA,CAAA;YAClBO,GAAKD,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,KAAA,CAAA;YACzBQ,UAAYF,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCS,UAAYH,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCU,QAAUJ,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,UAAA,CAAA;YAC9BW,WAAaL,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,aAAA,CAAA;AACjCE,YAAAA,MAAAA,EAAQI,KAAKN,MAAQ,EAAA,QAAA;AACvB,SAAA;QACAa,MAAQ,EAAA;YACNC,MAAQC,EAAAA,OAAAA,CAAQf,MAAQgB,EAAAA,GAAAA,CAAI,oBAAsBd,EAAAA,MAAAA,CAAAA;AACpD;AACF,KAAA;;;;"}
+49
View File
@@ -0,0 +1,49 @@
import _ from 'lodash';
import type { StrapiOptions } from '../Strapi';
export declare const loadConfiguration: (opts: StrapiOptions) => {
launchedAt: number;
autoReload: boolean;
environment: string | undefined;
uuid: any;
installId: any;
packageJsonStrapi: Pick<any, string | number | symbol>;
info: any;
admin: {
serveAdminPanel: boolean;
};
} & {
server: {
host: string;
port: number;
proxy: false;
cron: {
enabled: false;
};
admin: {
autoOpen: false;
};
dirs: {
public: string;
};
transfer: {
remote: {
enabled: true;
};
};
logger: {
updates: {
enabled: true;
};
startup: {
enabled: true;
};
};
};
admin: {};
api: {
rest: {
prefix: string;
};
};
} & _.Omit<Record<string, unknown>, "plugins"> & Record<string, unknown>;
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/configuration/index.ts"],"names":[],"mappings":"AAGA,OAAO,CAAC,MAAM,QAAQ,CAAC;AAUvB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAqC/C,eAAO,MAAM,iBAAiB,SAAU,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wEAkDpD,CAAC"}
+92
View File
@@ -0,0 +1,92 @@
'use strict';
var os = require('os');
var path = require('path');
var _ = require('lodash');
var fp = require('lodash/fp');
var dotenv = require('dotenv');
var strapiUtils = require('@strapi/utils');
var urls = require('./urls.js');
var configLoader = require('./config-loader.js');
var getDirs = require('./get-dirs.js');
var _package = require('../package.json.js');
dotenv.config({
path: process.env.ENV_PATH
});
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const defaultConfig = {
server: {
host: process.env.HOST || os.hostname() || 'localhost',
port: Number(process.env.PORT) || 1337,
proxy: false,
cron: {
enabled: false
},
admin: {
autoOpen: false
},
dirs: {
public: './public'
},
transfer: {
remote: {
enabled: true
}
},
logger: {
updates: {
enabled: true
},
startup: {
enabled: true
}
}
},
admin: {},
api: {
rest: {
prefix: '/api'
}
}
};
const loadConfiguration = (opts)=>{
const { appDir, distDir, autoReload = false, serveAdminPanel = true } = opts;
const pkgJSON = require(path.resolve(appDir, 'package.json'));
const configDir = path.resolve(distDir || process.cwd(), 'config');
const rootConfig = {
launchedAt: Date.now(),
autoReload,
environment: process.env.NODE_ENV,
uuid: _.get(pkgJSON, 'strapi.uuid'),
installId: _.get(pkgJSON, 'strapi.installId'),
packageJsonStrapi: _.omit(_.get(pkgJSON, 'strapi', {}), 'uuid'),
info: {
...pkgJSON,
strapi: _package.version
},
admin: {
serveAdminPanel
}
};
// See packages/core/core/src/domain/module/index.ts for plugin config loading
const baseConfig = fp.omit('plugins', configLoader(configDir)); // plugin config will be loaded later
const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV);
const envConfig = configLoader(envDir);
const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);
const { serverUrl, adminUrl } = urls.getConfigUrls(config);
const serverAbsoluteUrl = urls.getAbsoluteServerUrl(config);
const adminAbsoluteUrl = urls.getAbsoluteAdminUrl(config);
const sameOrigin = new URL(adminAbsoluteUrl).origin === new URL(serverAbsoluteUrl).origin;
const adminPath = sameOrigin ? adminUrl.replace(strapiUtils.strings.getCommonPath(serverUrl, adminUrl), '') : new URL(adminUrl).pathname;
_.set(config, 'server.url', serverUrl);
_.set(config, 'server.absoluteUrl', serverAbsoluteUrl);
_.set(config, 'admin.url', adminUrl);
_.set(config, 'admin.path', adminPath);
_.set(config, 'admin.absoluteUrl', adminAbsoluteUrl);
_.set(config, 'dirs', getDirs.getDirs(opts, config));
return config;
};
exports.loadConfiguration = loadConfiguration;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../src/configuration/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-var-requires */\nimport os from 'os';\nimport path from 'path';\nimport _ from 'lodash';\nimport { omit } from 'lodash/fp';\nimport dotenv from 'dotenv';\nimport type { Core } from '@strapi/types';\nimport { strings } from '@strapi/utils';\n\nimport { getConfigUrls, getAbsoluteAdminUrl, getAbsoluteServerUrl } from './urls';\nimport loadConfigDir from './config-loader';\nimport { getDirs } from './get-dirs';\n\nimport type { StrapiOptions } from '../Strapi';\nimport { version as strapiVersion } from '../../package.json';\n\ndotenv.config({ path: process.env.ENV_PATH });\n\nprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';\n\nconst defaultConfig = {\n server: {\n host: process.env.HOST || os.hostname() || 'localhost',\n port: Number(process.env.PORT) || 1337,\n proxy: false,\n cron: { enabled: false },\n admin: { autoOpen: false },\n dirs: { public: './public' },\n transfer: {\n remote: {\n enabled: true,\n },\n },\n logger: {\n updates: {\n enabled: true,\n },\n startup: {\n enabled: true,\n },\n },\n } satisfies Partial<Core.Config.Server>,\n admin: {} satisfies Partial<Core.Config.Admin>,\n api: {\n rest: {\n prefix: '/api',\n },\n } satisfies Partial<Core.Config.Api>,\n};\n\nexport const loadConfiguration = (opts: StrapiOptions) => {\n const { appDir, distDir, autoReload = false, serveAdminPanel = true } = opts;\n\n const pkgJSON = require(path.resolve(appDir, 'package.json'));\n\n const configDir = path.resolve(distDir || process.cwd(), 'config');\n\n const rootConfig = {\n launchedAt: Date.now(),\n autoReload,\n environment: process.env.NODE_ENV,\n uuid: _.get(pkgJSON, 'strapi.uuid'),\n installId: _.get(pkgJSON, 'strapi.installId'),\n packageJsonStrapi: _.omit(_.get(pkgJSON, 'strapi', {}), 'uuid'),\n info: {\n ...pkgJSON,\n strapi: strapiVersion,\n },\n admin: {\n serveAdminPanel,\n },\n };\n\n // See packages/core/core/src/domain/module/index.ts for plugin config loading\n const baseConfig = omit('plugins', loadConfigDir(configDir)); // plugin config will be loaded later\n\n const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV as string);\n const envConfig = loadConfigDir(envDir);\n\n const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);\n\n const { serverUrl, adminUrl } = getConfigUrls(config);\n\n const serverAbsoluteUrl = getAbsoluteServerUrl(config);\n const adminAbsoluteUrl = getAbsoluteAdminUrl(config);\n\n const sameOrigin = new URL(adminAbsoluteUrl).origin === new URL(serverAbsoluteUrl).origin;\n\n const adminPath = sameOrigin\n ? adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '')\n : new URL(adminUrl).pathname;\n\n _.set(config, 'server.url', serverUrl);\n _.set(config, 'server.absoluteUrl', serverAbsoluteUrl);\n _.set(config, 'admin.url', adminUrl);\n _.set(config, 'admin.path', adminPath);\n _.set(config, 'admin.absoluteUrl', adminAbsoluteUrl);\n _.set(config, 'dirs', getDirs(opts, config));\n\n return config;\n};\n"],"names":["dotenv","config","path","process","env","ENV_PATH","NODE_ENV","defaultConfig","server","host","HOST","os","hostname","port","Number","PORT","proxy","cron","enabled","admin","autoOpen","dirs","public","transfer","remote","logger","updates","startup","api","rest","prefix","loadConfiguration","opts","appDir","distDir","autoReload","serveAdminPanel","pkgJSON","require","resolve","configDir","cwd","rootConfig","launchedAt","Date","now","environment","uuid","_","get","installId","packageJsonStrapi","omit","info","strapi","strapiVersion","baseConfig","loadConfigDir","envDir","envConfig","merge","serverUrl","adminUrl","getConfigUrls","serverAbsoluteUrl","getAbsoluteServerUrl","adminAbsoluteUrl","getAbsoluteAdminUrl","sameOrigin","URL","origin","adminPath","replace","strings","getCommonPath","pathname","set","getDirs"],"mappings":";;;;;;;;;;;;;AAgBAA,MAAAA,CAAOC,MAAM,CAAC;IAAEC,IAAMC,EAAAA,OAAAA,CAAQC,GAAG,CAACC;AAAS,CAAA,CAAA;AAE3CF,OAAQC,CAAAA,GAAG,CAACE,QAAQ,GAAGH,QAAQC,GAAG,CAACE,QAAQ,IAAI,aAAA;AAE/C,MAAMC,aAAgB,GAAA;IACpBC,MAAQ,EAAA;AACNC,QAAAA,IAAAA,EAAMN,QAAQC,GAAG,CAACM,IAAI,IAAIC,EAAAA,CAAGC,QAAQ,EAAM,IAAA,WAAA;AAC3CC,QAAAA,IAAAA,EAAMC,MAAOX,CAAAA,OAAAA,CAAQC,GAAG,CAACW,IAAI,CAAK,IAAA,IAAA;QAClCC,KAAO,EAAA,KAAA;QACPC,IAAM,EAAA;YAAEC,OAAS,EAAA;AAAM,SAAA;QACvBC,KAAO,EAAA;YAAEC,QAAU,EAAA;AAAM,SAAA;QACzBC,IAAM,EAAA;YAAEC,MAAQ,EAAA;AAAW,SAAA;QAC3BC,QAAU,EAAA;YACRC,MAAQ,EAAA;gBACNN,OAAS,EAAA;AACX;AACF,SAAA;QACAO,MAAQ,EAAA;YACNC,OAAS,EAAA;gBACPR,OAAS,EAAA;AACX,aAAA;YACAS,OAAS,EAAA;gBACPT,OAAS,EAAA;AACX;AACF;AACF,KAAA;AACAC,IAAAA,KAAAA,EAAO,EAAC;IACRS,GAAK,EAAA;QACHC,IAAM,EAAA;YACJC,MAAQ,EAAA;AACV;AACF;AACF,CAAA;AAEO,MAAMC,oBAAoB,CAACC,IAAAA,GAAAA;IAChC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAEC,UAAa,GAAA,KAAK,EAAEC,eAAAA,GALine truncated
+90
View File
@@ -0,0 +1,90 @@
import os from 'os';
import path from 'path';
import _ from 'lodash';
import { omit } from 'lodash/fp';
import dotenv from 'dotenv';
import { strings } from '@strapi/utils';
import { getConfigUrls, getAbsoluteServerUrl, getAbsoluteAdminUrl } from './urls.mjs';
import loadConfigDir from './config-loader.mjs';
import { getDirs } from './get-dirs.mjs';
import { version } from '../package.json.mjs';
dotenv.config({
path: process.env.ENV_PATH
});
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const defaultConfig = {
server: {
host: process.env.HOST || os.hostname() || 'localhost',
port: Number(process.env.PORT) || 1337,
proxy: false,
cron: {
enabled: false
},
admin: {
autoOpen: false
},
dirs: {
public: './public'
},
transfer: {
remote: {
enabled: true
}
},
logger: {
updates: {
enabled: true
},
startup: {
enabled: true
}
}
},
admin: {},
api: {
rest: {
prefix: '/api'
}
}
};
const loadConfiguration = (opts)=>{
const { appDir, distDir, autoReload = false, serveAdminPanel = true } = opts;
const pkgJSON = require(path.resolve(appDir, 'package.json'));
const configDir = path.resolve(distDir || process.cwd(), 'config');
const rootConfig = {
launchedAt: Date.now(),
autoReload,
environment: process.env.NODE_ENV,
uuid: _.get(pkgJSON, 'strapi.uuid'),
installId: _.get(pkgJSON, 'strapi.installId'),
packageJsonStrapi: _.omit(_.get(pkgJSON, 'strapi', {}), 'uuid'),
info: {
...pkgJSON,
strapi: version
},
admin: {
serveAdminPanel
}
};
// See packages/core/core/src/domain/module/index.ts for plugin config loading
const baseConfig = omit('plugins', loadConfigDir(configDir)); // plugin config will be loaded later
const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV);
const envConfig = loadConfigDir(envDir);
const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);
const { serverUrl, adminUrl } = getConfigUrls(config);
const serverAbsoluteUrl = getAbsoluteServerUrl(config);
const adminAbsoluteUrl = getAbsoluteAdminUrl(config);
const sameOrigin = new URL(adminAbsoluteUrl).origin === new URL(serverAbsoluteUrl).origin;
const adminPath = sameOrigin ? adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '') : new URL(adminUrl).pathname;
_.set(config, 'server.url', serverUrl);
_.set(config, 'server.absoluteUrl', serverAbsoluteUrl);
_.set(config, 'admin.url', adminUrl);
_.set(config, 'admin.path', adminPath);
_.set(config, 'admin.absoluteUrl', adminAbsoluteUrl);
_.set(config, 'dirs', getDirs(opts, config));
return config;
};
export { loadConfiguration };
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../src/configuration/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-var-requires */\nimport os from 'os';\nimport path from 'path';\nimport _ from 'lodash';\nimport { omit } from 'lodash/fp';\nimport dotenv from 'dotenv';\nimport type { Core } from '@strapi/types';\nimport { strings } from '@strapi/utils';\n\nimport { getConfigUrls, getAbsoluteAdminUrl, getAbsoluteServerUrl } from './urls';\nimport loadConfigDir from './config-loader';\nimport { getDirs } from './get-dirs';\n\nimport type { StrapiOptions } from '../Strapi';\nimport { version as strapiVersion } from '../../package.json';\n\ndotenv.config({ path: process.env.ENV_PATH });\n\nprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';\n\nconst defaultConfig = {\n server: {\n host: process.env.HOST || os.hostname() || 'localhost',\n port: Number(process.env.PORT) || 1337,\n proxy: false,\n cron: { enabled: false },\n admin: { autoOpen: false },\n dirs: { public: './public' },\n transfer: {\n remote: {\n enabled: true,\n },\n },\n logger: {\n updates: {\n enabled: true,\n },\n startup: {\n enabled: true,\n },\n },\n } satisfies Partial<Core.Config.Server>,\n admin: {} satisfies Partial<Core.Config.Admin>,\n api: {\n rest: {\n prefix: '/api',\n },\n } satisfies Partial<Core.Config.Api>,\n};\n\nexport const loadConfiguration = (opts: StrapiOptions) => {\n const { appDir, distDir, autoReload = false, serveAdminPanel = true } = opts;\n\n const pkgJSON = require(path.resolve(appDir, 'package.json'));\n\n const configDir = path.resolve(distDir || process.cwd(), 'config');\n\n const rootConfig = {\n launchedAt: Date.now(),\n autoReload,\n environment: process.env.NODE_ENV,\n uuid: _.get(pkgJSON, 'strapi.uuid'),\n installId: _.get(pkgJSON, 'strapi.installId'),\n packageJsonStrapi: _.omit(_.get(pkgJSON, 'strapi', {}), 'uuid'),\n info: {\n ...pkgJSON,\n strapi: strapiVersion,\n },\n admin: {\n serveAdminPanel,\n },\n };\n\n // See packages/core/core/src/domain/module/index.ts for plugin config loading\n const baseConfig = omit('plugins', loadConfigDir(configDir)); // plugin config will be loaded later\n\n const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV as string);\n const envConfig = loadConfigDir(envDir);\n\n const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);\n\n const { serverUrl, adminUrl } = getConfigUrls(config);\n\n const serverAbsoluteUrl = getAbsoluteServerUrl(config);\n const adminAbsoluteUrl = getAbsoluteAdminUrl(config);\n\n const sameOrigin = new URL(adminAbsoluteUrl).origin === new URL(serverAbsoluteUrl).origin;\n\n const adminPath = sameOrigin\n ? adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '')\n : new URL(adminUrl).pathname;\n\n _.set(config, 'server.url', serverUrl);\n _.set(config, 'server.absoluteUrl', serverAbsoluteUrl);\n _.set(config, 'admin.url', adminUrl);\n _.set(config, 'admin.path', adminPath);\n _.set(config, 'admin.absoluteUrl', adminAbsoluteUrl);\n _.set(config, 'dirs', getDirs(opts, config));\n\n return config;\n};\n"],"names":["dotenv","config","path","process","env","ENV_PATH","NODE_ENV","defaultConfig","server","host","HOST","os","hostname","port","Number","PORT","proxy","cron","enabled","admin","autoOpen","dirs","public","transfer","remote","logger","updates","startup","api","rest","prefix","loadConfiguration","opts","appDir","distDir","autoReload","serveAdminPanel","pkgJSON","require","resolve","configDir","cwd","rootConfig","launchedAt","Date","now","environment","uuid","_","get","installId","packageJsonStrapi","omit","info","strapi","strapiVersion","baseConfig","loadConfigDir","envDir","envConfig","merge","serverUrl","adminUrl","getConfigUrls","serverAbsoluteUrl","getAbsoluteServerUrl","adminAbsoluteUrl","getAbsoluteAdminUrl","sameOrigin","URL","origin","adminPath","replace","strings","getCommonPath","pathname","set","getDirs"],"mappings":";;;;;;;;;;;AAgBAA,MAAAA,CAAOC,MAAM,CAAC;IAAEC,IAAMC,EAAAA,OAAAA,CAAQC,GAAG,CAACC;AAAS,CAAA,CAAA;AAE3CF,OAAQC,CAAAA,GAAG,CAACE,QAAQ,GAAGH,QAAQC,GAAG,CAACE,QAAQ,IAAI,aAAA;AAE/C,MAAMC,aAAgB,GAAA;IACpBC,MAAQ,EAAA;AACNC,QAAAA,IAAAA,EAAMN,QAAQC,GAAG,CAACM,IAAI,IAAIC,EAAAA,CAAGC,QAAQ,EAAM,IAAA,WAAA;AAC3CC,QAAAA,IAAAA,EAAMC,MAAOX,CAAAA,OAAAA,CAAQC,GAAG,CAACW,IAAI,CAAK,IAAA,IAAA;QAClCC,KAAO,EAAA,KAAA;QACPC,IAAM,EAAA;YAAEC,OAAS,EAAA;AAAM,SAAA;QACvBC,KAAO,EAAA;YAAEC,QAAU,EAAA;AAAM,SAAA;QACzBC,IAAM,EAAA;YAAEC,MAAQ,EAAA;AAAW,SAAA;QAC3BC,QAAU,EAAA;YACRC,MAAQ,EAAA;gBACNN,OAAS,EAAA;AACX;AACF,SAAA;QACAO,MAAQ,EAAA;YACNC,OAAS,EAAA;gBACPR,OAAS,EAAA;AACX,aAAA;YACAS,OAAS,EAAA;gBACPT,OAAS,EAAA;AACX;AACF;AACF,KAAA;AACAC,IAAAA,KAAAA,EAAO,EAAC;IACRS,GAAK,EAAA;QACHC,IAAM,EAAA;YACJC,MAAQ,EAAA;AACV;AACF;AACF,CAAA;AAEO,MAAMC,oBAAoB,CAACC,IAAAA,GAAAA;IAChC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAEC,UAAa,GAAA,KAAK,EAAEC,eAAAA,GAALine truncated
+8
View File
@@ -0,0 +1,8 @@
export declare const getConfigUrls: (config: Record<string, unknown>, forAdminBuild?: boolean) => {
serverUrl: string;
adminUrl: string;
adminPath: string;
};
export declare const getAbsoluteAdminUrl: (config: Record<string, unknown>, forAdminBuild?: boolean) => string;
export declare const getAbsoluteServerUrl: (config: Record<string, unknown>, forAdminBuild?: boolean) => string;
//# sourceMappingURL=urls.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"urls.d.ts","sourceRoot":"","sources":["../../src/configuration/urls.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,aAAa,WAAY,OAAO,MAAM,EAAE,OAAO,CAAC;;;;CA0D5D,CAAC;AA6BF,eAAO,MAAM,mBAAmB,WAzBrB,OAAO,MAAM,EAAE,OAAO,CAAC,oCAyBwB,CAAC;AAC3D,eAAO,MAAM,oBAAoB,WA1BtB,OAAO,MAAM,EAAE,OAAO,CAAC,oCA0B0B,CAAC"}
+81
View File
@@ -0,0 +1,81 @@
'use strict';
var _ = require('lodash');
var strapiUtils = require('@strapi/utils');
var node_net = require('node:net');
const getConfigUrls = (config, forAdminBuild = false)=>{
const serverConfig = config.server;
const adminConfig = config.admin;
// Defines serverUrl value
let serverUrl = _.get(serverConfig, 'url', '');
serverUrl = _.trim(serverUrl, '/ ');
if (typeof serverUrl !== 'string') {
throw new Error('Invalid server url config. Make sure the url is a string.');
}
if (serverUrl.startsWith('http')) {
try {
serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');
} catch (e) {
throw new Error('Invalid server url config. Make sure the url defined in server.js is valid.');
}
} else if (serverUrl !== '') {
serverUrl = `/${serverUrl}`;
}
// Defines adminUrl value
let adminUrl = _.get(adminConfig, 'url', '/admin');
adminUrl = _.trim(adminUrl, '/ ');
if (typeof adminUrl !== 'string') {
throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');
}
if (adminUrl.startsWith('http')) {
try {
adminUrl = _.trim(new URL(adminUrl).toString(), '/');
} catch (e) {
throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');
}
} else {
adminUrl = `${serverUrl}/${adminUrl}`;
}
// Defines adminPath value
let adminPath = adminUrl;
if (serverUrl.startsWith('http') && adminUrl.startsWith('http') && new URL(adminUrl).origin === new URL(serverUrl).origin && !forAdminBuild) {
adminPath = adminUrl.replace(strapiUtils.strings.getCommonPath(serverUrl, adminUrl), '');
adminPath = `/${_.trim(adminPath, '/')}`;
} else if (adminUrl.startsWith('http')) {
adminPath = new URL(adminUrl).pathname;
}
return {
serverUrl,
adminUrl,
adminPath
};
};
const getAbsoluteUrl = (adminOrServer)=>(config, forAdminBuild = false)=>{
const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);
const url = adminOrServer === 'server' ? serverUrl : adminUrl;
if (url.startsWith('http')) {
return url;
}
const serverConfig = config.server;
const isLocalhost = config.environment === 'development' && [
'127.0.0.1',
'0.0.0.0',
'::1',
'::'
].includes(serverConfig.host);
if (isLocalhost) {
return `http://localhost:${serverConfig.port}${url}`;
}
if (node_net.isIP(serverConfig.host) === 6) {
return `http://[${serverConfig.host}]:${serverConfig.port}${url}`;
}
return `http://${serverConfig.host}:${serverConfig.port}${url}`;
};
const getAbsoluteAdminUrl = getAbsoluteUrl('admin');
const getAbsoluteServerUrl = getAbsoluteUrl('server');
exports.getAbsoluteAdminUrl = getAbsoluteAdminUrl;
exports.getAbsoluteServerUrl = getAbsoluteServerUrl;
exports.getConfigUrls = getConfigUrls;
//# sourceMappingURL=urls.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"urls.js","sources":["../../src/configuration/urls.ts"],"sourcesContent":["import _ from 'lodash';\nimport { strings } from '@strapi/utils';\nimport { isIP } from 'node:net';\n\ninterface ServerConfig {\n url: string;\n host: string;\n port: number | string;\n}\n\nexport const getConfigUrls = (config: Record<string, unknown>, forAdminBuild = false) => {\n const serverConfig = config.server as ServerConfig;\n const adminConfig = config.admin;\n\n // Defines serverUrl value\n let serverUrl = _.get(serverConfig, 'url', '');\n serverUrl = _.trim(serverUrl, '/ ');\n if (typeof serverUrl !== 'string') {\n throw new Error('Invalid server url config. Make sure the url is a string.');\n }\n\n if (serverUrl.startsWith('http')) {\n try {\n serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');\n } catch (e) {\n throw new Error(\n 'Invalid server url config. Make sure the url defined in server.js is valid.'\n );\n }\n } else if (serverUrl !== '') {\n serverUrl = `/${serverUrl}`;\n }\n\n // Defines adminUrl value\n let adminUrl = _.get(adminConfig, 'url', '/admin');\n adminUrl = _.trim(adminUrl, '/ ');\n if (typeof adminUrl !== 'string') {\n throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');\n }\n if (adminUrl.startsWith('http')) {\n try {\n adminUrl = _.trim(new URL(adminUrl).toString(), '/');\n } catch (e) {\n throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');\n }\n } else {\n adminUrl = `${serverUrl}/${adminUrl}`;\n }\n\n // Defines adminPath value\n let adminPath = adminUrl;\n if (\n serverUrl.startsWith('http') &&\n adminUrl.startsWith('http') &&\n new URL(adminUrl).origin === new URL(serverUrl).origin &&\n !forAdminBuild\n ) {\n adminPath = adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '');\n adminPath = `/${_.trim(adminPath, '/')}`;\n } else if (adminUrl.startsWith('http')) {\n adminPath = new URL(adminUrl).pathname;\n }\n\n return {\n serverUrl,\n adminUrl,\n adminPath,\n };\n};\n\nconst getAbsoluteUrl =\n (adminOrServer: 'admin' | 'server') =>\n (config: Record<string, unknown>, forAdminBuild = false) => {\n const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);\n const url = adminOrServer === 'server' ? serverUrl : adminUrl;\n\n if (url.startsWith('http')) {\n return url;\n }\n\n const serverConfig = config.server as ServerConfig;\n\n const isLocalhost =\n config.environment === 'development' &&\n ['127.0.0.1', '0.0.0.0', '::1', '::'].includes(serverConfig.host);\n\n if (isLocalhost) {\n return `http://localhost:${serverConfig.port}${url}`;\n }\n\n if (isIP(serverConfig.host) === 6) {\n return `http://[${serverConfig.host}]:${serverConfig.port}${url}`;\n }\n\n return `http://${serverConfig.host}:${serverConfig.port}${url}`;\n };\n\nexport const getAbsoluteAdminUrl = getAbsoluteUrl('admin');\nexport const getAbsoluteServerUrl = getAbsoluteUrl('server');\n"],"names":["getConfigUrls","config","forAdminBuild","serverConfig","server","adminConfig","admin","serverUrl","_","get","trim","Error","startsWith","URL","url","toString","e","adminUrl","adminPath","origin","replace","strings","getCommonPath","pathname","getAbsoluteUrl","adminOrServer","isLocalhost","environment","includes","host","port","isIP","getAbsoluteAdminUrl","getAbsoluteServerUrl"],"mappings":";;;;;;AAUaA,MAAAA,aAAAA,GAAgB,CAACC,MAAAA,EAAiCC,gBAAgB,KAAK,GAAA;IAClF,MAAMC,YAAAA,GAAeF,OAAOG,MAAM;IAClC,MAAMC,WAAAA,GAAcJ,OAAOK,KAAK;;AAGhC,IAAA,IAAIC,SAAYC,GAAAA,CAAAA,CAAEC,GAAG,CAACN,cAAc,KAAO,EAAA,EAAA,CAAA;IAC3CI,SAAYC,GAAAA,CAAAA,CAAEE,IAAI,CAACH,SAAW,EAAA,IAAA,CAAA;IAC9B,IAAI,OAAOA,cAAc,QAAU,EAAA;AACjC,QAAA,MAAM,IAAII,KAAM,CAAA,2DAAA,CAAA;AAClB;IAEA,IAAIJ,SAAAA,CAAUK,UAAU,CAAC,MAAS,CAAA,EAAA;QAChC,IAAI;YACFL,SAAYC,GAAAA,CAAAA,CAAEE,IAAI,CAAC,IAAIG,IAAIV,YAAaW,CAAAA,GAAG,CAAEC,CAAAA,QAAQ,EAAI,EAAA,GAAA,CAAA;AAC3D,SAAA,CAAE,OAAOC,CAAG,EAAA;AACV,YAAA,MAAM,IAAIL,KACR,CAAA,6EAAA,CAAA;AAEJ;KACK,MAAA,IAAIJ,cAAc,EAAI,EAAA;AAC3BA,QAAAA,SAAAA,GAAY,CAAC,CAAC,EAAEA,SAAAA,CAAU,CAAC;AAC7B;;AAGA,IAAA,IAAIU,QAAWT,GAAAA,CAAAA,CAAEC,GAAG,CAACJ,aAAa,KAAO,EAAA,QAAA,CAAA;IACzCY,QAAWT,GAAAA,CAAAA,CAAEE,IAAI,CAACO,QAAU,EAAA,IAAA,CAAA;IAC5B,IAAI,OAAOA,aAAa,QAAU,EAAA;AAChC,QAAA,MAAM,IAAIN,KAAM,CAAA,oEAAA,CAAA;AAClB;IACA,IAAIM,QAAAA,CAASL,UAAU,CAAC,MAAS,CAAA,EAAA;QAC/B,IAAI;AACFK,YAAAA,QAAAA,GAAWT,EAAEE,IAAI,CAAC,IAAIG,GAAII,CAAAA,QAAAA,CAAAA,CAAUF,QAAQ,EAAI,EAAA,GAAA,CAAA;AAClD,SAAA,CAAE,OAAOC,CAAG,EAAA;AACV,YAAA,MAAM,IAAIL,KAAM,CAAA,4EAAA,CAAA;AAClB;KACK,MAAA;AACLM,QAAAA,QAAAA,GAAW,CAAC,EAAEV,SAAAA,CAAU,CAAC,EAAEU,SAAS,CAAC;AACvC;;AAGA,IAAA,IAAIC,SAAYD,GAAAA,QAAAA;AAChB,IAAA,IACEV,UAAUK,UAAU,CAAC,WACrBK,QAASL,CAAAA,UAAU,CAAC,MACpB,CAAA,IAAA,IAAIC,IAAII,QAAUE,CAAAA,CAAAA,MAAM,KAAK,IAAIN,GAAAA,CAAIN,WAAWY,MAAM,IACtD,CAACjB,aACD,EAAA;AACAgB,QAAAA,SAAAA,GAAYD,SAASG,Line truncated
+77
View File
@@ -0,0 +1,77 @@
import _ from 'lodash';
import { strings } from '@strapi/utils';
import { isIP } from 'node:net';
const getConfigUrls = (config, forAdminBuild = false)=>{
const serverConfig = config.server;
const adminConfig = config.admin;
// Defines serverUrl value
let serverUrl = _.get(serverConfig, 'url', '');
serverUrl = _.trim(serverUrl, '/ ');
if (typeof serverUrl !== 'string') {
throw new Error('Invalid server url config. Make sure the url is a string.');
}
if (serverUrl.startsWith('http')) {
try {
serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');
} catch (e) {
throw new Error('Invalid server url config. Make sure the url defined in server.js is valid.');
}
} else if (serverUrl !== '') {
serverUrl = `/${serverUrl}`;
}
// Defines adminUrl value
let adminUrl = _.get(adminConfig, 'url', '/admin');
adminUrl = _.trim(adminUrl, '/ ');
if (typeof adminUrl !== 'string') {
throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');
}
if (adminUrl.startsWith('http')) {
try {
adminUrl = _.trim(new URL(adminUrl).toString(), '/');
} catch (e) {
throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');
}
} else {
adminUrl = `${serverUrl}/${adminUrl}`;
}
// Defines adminPath value
let adminPath = adminUrl;
if (serverUrl.startsWith('http') && adminUrl.startsWith('http') && new URL(adminUrl).origin === new URL(serverUrl).origin && !forAdminBuild) {
adminPath = adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '');
adminPath = `/${_.trim(adminPath, '/')}`;
} else if (adminUrl.startsWith('http')) {
adminPath = new URL(adminUrl).pathname;
}
return {
serverUrl,
adminUrl,
adminPath
};
};
const getAbsoluteUrl = (adminOrServer)=>(config, forAdminBuild = false)=>{
const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);
const url = adminOrServer === 'server' ? serverUrl : adminUrl;
if (url.startsWith('http')) {
return url;
}
const serverConfig = config.server;
const isLocalhost = config.environment === 'development' && [
'127.0.0.1',
'0.0.0.0',
'::1',
'::'
].includes(serverConfig.host);
if (isLocalhost) {
return `http://localhost:${serverConfig.port}${url}`;
}
if (isIP(serverConfig.host) === 6) {
return `http://[${serverConfig.host}]:${serverConfig.port}${url}`;
}
return `http://${serverConfig.host}:${serverConfig.port}${url}`;
};
const getAbsoluteAdminUrl = getAbsoluteUrl('admin');
const getAbsoluteServerUrl = getAbsoluteUrl('server');
export { getAbsoluteAdminUrl, getAbsoluteServerUrl, getConfigUrls };
//# sourceMappingURL=urls.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"urls.mjs","sources":["../../src/configuration/urls.ts"],"sourcesContent":["import _ from 'lodash';\nimport { strings } from '@strapi/utils';\nimport { isIP } from 'node:net';\n\ninterface ServerConfig {\n url: string;\n host: string;\n port: number | string;\n}\n\nexport const getConfigUrls = (config: Record<string, unknown>, forAdminBuild = false) => {\n const serverConfig = config.server as ServerConfig;\n const adminConfig = config.admin;\n\n // Defines serverUrl value\n let serverUrl = _.get(serverConfig, 'url', '');\n serverUrl = _.trim(serverUrl, '/ ');\n if (typeof serverUrl !== 'string') {\n throw new Error('Invalid server url config. Make sure the url is a string.');\n }\n\n if (serverUrl.startsWith('http')) {\n try {\n serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');\n } catch (e) {\n throw new Error(\n 'Invalid server url config. Make sure the url defined in server.js is valid.'\n );\n }\n } else if (serverUrl !== '') {\n serverUrl = `/${serverUrl}`;\n }\n\n // Defines adminUrl value\n let adminUrl = _.get(adminConfig, 'url', '/admin');\n adminUrl = _.trim(adminUrl, '/ ');\n if (typeof adminUrl !== 'string') {\n throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');\n }\n if (adminUrl.startsWith('http')) {\n try {\n adminUrl = _.trim(new URL(adminUrl).toString(), '/');\n } catch (e) {\n throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');\n }\n } else {\n adminUrl = `${serverUrl}/${adminUrl}`;\n }\n\n // Defines adminPath value\n let adminPath = adminUrl;\n if (\n serverUrl.startsWith('http') &&\n adminUrl.startsWith('http') &&\n new URL(adminUrl).origin === new URL(serverUrl).origin &&\n !forAdminBuild\n ) {\n adminPath = adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '');\n adminPath = `/${_.trim(adminPath, '/')}`;\n } else if (adminUrl.startsWith('http')) {\n adminPath = new URL(adminUrl).pathname;\n }\n\n return {\n serverUrl,\n adminUrl,\n adminPath,\n };\n};\n\nconst getAbsoluteUrl =\n (adminOrServer: 'admin' | 'server') =>\n (config: Record<string, unknown>, forAdminBuild = false) => {\n const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);\n const url = adminOrServer === 'server' ? serverUrl : adminUrl;\n\n if (url.startsWith('http')) {\n return url;\n }\n\n const serverConfig = config.server as ServerConfig;\n\n const isLocalhost =\n config.environment === 'development' &&\n ['127.0.0.1', '0.0.0.0', '::1', '::'].includes(serverConfig.host);\n\n if (isLocalhost) {\n return `http://localhost:${serverConfig.port}${url}`;\n }\n\n if (isIP(serverConfig.host) === 6) {\n return `http://[${serverConfig.host}]:${serverConfig.port}${url}`;\n }\n\n return `http://${serverConfig.host}:${serverConfig.port}${url}`;\n };\n\nexport const getAbsoluteAdminUrl = getAbsoluteUrl('admin');\nexport const getAbsoluteServerUrl = getAbsoluteUrl('server');\n"],"names":["getConfigUrls","config","forAdminBuild","serverConfig","server","adminConfig","admin","serverUrl","_","get","trim","Error","startsWith","URL","url","toString","e","adminUrl","adminPath","origin","replace","strings","getCommonPath","pathname","getAbsoluteUrl","adminOrServer","isLocalhost","environment","includes","host","port","isIP","getAbsoluteAdminUrl","getAbsoluteServerUrl"],"mappings":";;;;AAUaA,MAAAA,aAAAA,GAAgB,CAACC,MAAAA,EAAiCC,gBAAgB,KAAK,GAAA;IAClF,MAAMC,YAAAA,GAAeF,OAAOG,MAAM;IAClC,MAAMC,WAAAA,GAAcJ,OAAOK,KAAK;;AAGhC,IAAA,IAAIC,SAAYC,GAAAA,CAAAA,CAAEC,GAAG,CAACN,cAAc,KAAO,EAAA,EAAA,CAAA;IAC3CI,SAAYC,GAAAA,CAAAA,CAAEE,IAAI,CAACH,SAAW,EAAA,IAAA,CAAA;IAC9B,IAAI,OAAOA,cAAc,QAAU,EAAA;AACjC,QAAA,MAAM,IAAII,KAAM,CAAA,2DAAA,CAAA;AAClB;IAEA,IAAIJ,SAAAA,CAAUK,UAAU,CAAC,MAAS,CAAA,EAAA;QAChC,IAAI;YACFL,SAAYC,GAAAA,CAAAA,CAAEE,IAAI,CAAC,IAAIG,IAAIV,YAAaW,CAAAA,GAAG,CAAEC,CAAAA,QAAQ,EAAI,EAAA,GAAA,CAAA;AAC3D,SAAA,CAAE,OAAOC,CAAG,EAAA;AACV,YAAA,MAAM,IAAIL,KACR,CAAA,6EAAA,CAAA;AAEJ;KACK,MAAA,IAAIJ,cAAc,EAAI,EAAA;AAC3BA,QAAAA,SAAAA,GAAY,CAAC,CAAC,EAAEA,SAAAA,CAAU,CAAC;AAC7B;;AAGA,IAAA,IAAIU,QAAWT,GAAAA,CAAAA,CAAEC,GAAG,CAACJ,aAAa,KAAO,EAAA,QAAA,CAAA;IACzCY,QAAWT,GAAAA,CAAAA,CAAEE,IAAI,CAACO,QAAU,EAAA,IAAA,CAAA;IAC5B,IAAI,OAAOA,aAAa,QAAU,EAAA;AAChC,QAAA,MAAM,IAAIN,KAAM,CAAA,oEAAA,CAAA;AAClB;IACA,IAAIM,QAAAA,CAASL,UAAU,CAAC,MAAS,CAAA,EAAA;QAC/B,IAAI;AACFK,YAAAA,QAAAA,GAAWT,EAAEE,IAAI,CAAC,IAAIG,GAAII,CAAAA,QAAAA,CAAAA,CAAUF,QAAQ,EAAI,EAAA,GAAA,CAAA;AAClD,SAAA,CAAE,OAAOC,CAAG,EAAA;AACV,YAAA,MAAM,IAAIL,KAAM,CAAA,4EAAA,CAAA;AAClB;KACK,MAAA;AACLM,QAAAA,QAAAA,GAAW,CAAC,EAAEV,SAAAA,CAAU,CAAC,EAAEU,SAAS,CAAC;AACvC;;AAGA,IAAA,IAAIC,SAAYD,GAAAA,QAAAA;AAChB,IAAA,IACEV,UAAUK,UAAU,CAAC,WACrBK,QAASL,CAAAA,UAAU,CAAC,MACpB,CAAA,IAAA,IAAIC,IAAII,QAAUE,CAAAA,CAAAA,MAAM,KAAK,IAAIN,GAAAA,CAAIN,WAAWY,MAAM,IACtD,CAACjB,aACD,EAAA;AACAgB,QAAAA,SAAAA,GAAYD,SAASG,OLine truncated
+8
View File
@@ -0,0 +1,8 @@
import type { Core } from '@strapi/types';
export declare class Container implements Core.Container {
private registerMap;
private serviceMap;
add(name: string, resolver: unknown): this;
get(name: string, args?: unknown): any;
}
//# sourceMappingURL=container.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../src/container.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,qBAAa,SAAU,YAAW,IAAI,CAAC,SAAS;IAC9C,OAAO,CAAC,WAAW,CAA8B;IAEjD,OAAO,CAAC,UAAU,CAAa;IAE/B,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO;IASnC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO;CAoBjC"}
+34
View File
@@ -0,0 +1,34 @@
'use strict';
class Container {
add(name, resolver) {
if (this.registerMap.has(name)) {
throw new Error(`Cannot register already registered service ${name}`);
}
this.registerMap.set(name, resolver);
return this;
}
get(name, args) {
// TODO: handle singleton vs instantiation everytime
if (this.serviceMap.has(name)) {
return this.serviceMap.get(name);
}
if (this.registerMap.has(name)) {
const resolver = this.registerMap.get(name);
if (typeof resolver === 'function') {
this.serviceMap.set(name, resolver(this, args));
} else {
this.serviceMap.set(name, resolver);
}
return this.serviceMap.get(name);
}
throw new Error(`Could not resolve service ${name}`);
}
constructor(){
this.registerMap = new Map();
this.serviceMap = new Map();
}
}
exports.Container = Container;
//# sourceMappingURL=container.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"container.js","sources":["../src/container.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class Container implements Core.Container {\n private registerMap = new Map<string, unknown>();\n\n private serviceMap = new Map();\n\n add(name: string, resolver: unknown) {\n if (this.registerMap.has(name)) {\n throw new Error(`Cannot register already registered service ${name}`);\n }\n\n this.registerMap.set(name, resolver);\n return this;\n }\n\n get(name: string, args?: unknown) {\n // TODO: handle singleton vs instantiation everytime\n if (this.serviceMap.has(name)) {\n return this.serviceMap.get(name);\n }\n\n if (this.registerMap.has(name)) {\n const resolver = this.registerMap.get(name);\n\n if (typeof resolver === 'function') {\n this.serviceMap.set(name, resolver(this, args));\n } else {\n this.serviceMap.set(name, resolver);\n }\n\n return this.serviceMap.get(name);\n }\n\n throw new Error(`Could not resolve service ${name}`);\n }\n}\n"],"names":["Container","add","name","resolver","registerMap","has","Error","set","get","args","serviceMap","Map"],"mappings":";;AAEO,MAAMA,SAAAA,CAAAA;IAKXC,GAAIC,CAAAA,IAAY,EAAEC,QAAiB,EAAE;AACnC,QAAA,IAAI,IAAI,CAACC,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAM,IAAII,KAAM,CAAA,CAAC,2CAA2C,EAAEJ,KAAK,CAAC,CAAA;AACtE;AAEA,QAAA,IAAI,CAACE,WAAW,CAACG,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC3B,QAAA,OAAO,IAAI;AACb;IAEAK,GAAIN,CAAAA,IAAY,EAAEO,IAAc,EAAE;;AAEhC,QAAA,IAAI,IAAI,CAACC,UAAU,CAACL,GAAG,CAACH,IAAO,CAAA,EAAA;AAC7B,YAAA,OAAO,IAAI,CAACQ,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,IAAI,IAAI,CAACE,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAMC,WAAW,IAAI,CAACC,WAAW,CAACI,GAAG,CAACN,IAAAA,CAAAA;YAEtC,IAAI,OAAOC,aAAa,UAAY,EAAA;gBAClC,IAAI,CAACO,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAS,IAAI,EAAEM,IAAAA,CAAAA,CAAAA;aACpC,MAAA;AACL,gBAAA,IAAI,CAACC,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC5B;AAEA,YAAA,OAAO,IAAI,CAACO,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,MAAM,IAAII,KAAM,CAAA,CAAC,0BAA0B,EAAEJ,KAAK,CAAC,CAAA;AACrD;;AAhCQE,QAAAA,IAAAA,CAAAA,WAAAA,GAAc,IAAIO,GAAAA,EAAAA;AAElBD,QAAAA,IAAAA,CAAAA,UAAAA,GAAa,IAAIC,GAAAA,EAAAA;;AA+B3B;;;;"}
+32
View File
@@ -0,0 +1,32 @@
class Container {
add(name, resolver) {
if (this.registerMap.has(name)) {
throw new Error(`Cannot register already registered service ${name}`);
}
this.registerMap.set(name, resolver);
return this;
}
get(name, args) {
// TODO: handle singleton vs instantiation everytime
if (this.serviceMap.has(name)) {
return this.serviceMap.get(name);
}
if (this.registerMap.has(name)) {
const resolver = this.registerMap.get(name);
if (typeof resolver === 'function') {
this.serviceMap.set(name, resolver(this, args));
} else {
this.serviceMap.set(name, resolver);
}
return this.serviceMap.get(name);
}
throw new Error(`Could not resolve service ${name}`);
}
constructor(){
this.registerMap = new Map();
this.serviceMap = new Map();
}
}
export { Container };
//# sourceMappingURL=container.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"container.mjs","sources":["../src/container.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class Container implements Core.Container {\n private registerMap = new Map<string, unknown>();\n\n private serviceMap = new Map();\n\n add(name: string, resolver: unknown) {\n if (this.registerMap.has(name)) {\n throw new Error(`Cannot register already registered service ${name}`);\n }\n\n this.registerMap.set(name, resolver);\n return this;\n }\n\n get(name: string, args?: unknown) {\n // TODO: handle singleton vs instantiation everytime\n if (this.serviceMap.has(name)) {\n return this.serviceMap.get(name);\n }\n\n if (this.registerMap.has(name)) {\n const resolver = this.registerMap.get(name);\n\n if (typeof resolver === 'function') {\n this.serviceMap.set(name, resolver(this, args));\n } else {\n this.serviceMap.set(name, resolver);\n }\n\n return this.serviceMap.get(name);\n }\n\n throw new Error(`Could not resolve service ${name}`);\n }\n}\n"],"names":["Container","add","name","resolver","registerMap","has","Error","set","get","args","serviceMap","Map"],"mappings":"AAEO,MAAMA,SAAAA,CAAAA;IAKXC,GAAIC,CAAAA,IAAY,EAAEC,QAAiB,EAAE;AACnC,QAAA,IAAI,IAAI,CAACC,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAM,IAAII,KAAM,CAAA,CAAC,2CAA2C,EAAEJ,KAAK,CAAC,CAAA;AACtE;AAEA,QAAA,IAAI,CAACE,WAAW,CAACG,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC3B,QAAA,OAAO,IAAI;AACb;IAEAK,GAAIN,CAAAA,IAAY,EAAEO,IAAc,EAAE;;AAEhC,QAAA,IAAI,IAAI,CAACC,UAAU,CAACL,GAAG,CAACH,IAAO,CAAA,EAAA;AAC7B,YAAA,OAAO,IAAI,CAACQ,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,IAAI,IAAI,CAACE,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAMC,WAAW,IAAI,CAACC,WAAW,CAACI,GAAG,CAACN,IAAAA,CAAAA;YAEtC,IAAI,OAAOC,aAAa,UAAY,EAAA;gBAClC,IAAI,CAACO,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAS,IAAI,EAAEM,IAAAA,CAAAA,CAAAA;aACpC,MAAA;AACL,gBAAA,IAAI,CAACC,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC5B;AAEA,YAAA,OAAO,IAAI,CAACO,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,MAAM,IAAII,KAAM,CAAA,CAAC,0BAA0B,EAAEJ,KAAK,CAAC,CAAA;AACrD;;AAhCQE,QAAAA,IAAAA,CAAAA,WAAAA,GAAc,IAAIO,GAAAA,EAAAA;AAElBD,QAAAA,IAAAA,CAAAA,UAAAA,GAAa,IAAIC,GAAAA,EAAAA;;AA+B3B;;;;"}
@@ -0,0 +1,11 @@
import type { Core, Struct, Utils } from '@strapi/types';
interface Options {
contentType: Struct.CollectionTypeSchema;
}
/**
*
* Returns a collection type controller to handle default core-api actions
*/
declare const createCollectionTypeController: ({ contentType, }: Options) => Utils.PartialWithThis<Core.CoreAPI.Controller.CollectionType>;
export { createCollectionTypeController };
//# sourceMappingURL=collection-type.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"collection-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/collection-type.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAO,MAAM,eAAe,CAAC;AAG9D,UAAU,OAAO;IACf,WAAW,EAAE,MAAM,CAAC,oBAAoB,CAAC;CAC1C;AAED;;;GAGG;AACH,QAAA,MAAM,8BAA8B,qBAEjC,OAAO,KAAG,MAAM,eAAe,CAAC,KAAK,OAAO,CAAC,UAAU,CAAC,cAAc,CAoGxE,CAAC;AAEF,OAAO,EAAE,8BAA8B,EAAE,CAAC"}
@@ -0,0 +1,85 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
/**
*
* Returns a collection type controller to handle default core-api actions
*/ const createCollectionTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve records.
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { results, pagination } = await strapi.service(uid).find(sanitizedQuery);
const sanitizedResults = await this.sanitizeOutput(results, ctx);
return this.transformResponse(sanitizedResults, {
pagination
});
},
/**
* Retrieve a record
*/ async findOne (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).findOne(id, sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Create a record.
*/ async create (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!fp.isObject(body.data)) {
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).create({
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
ctx.status = 201;
return this.transformResponse(sanitizedEntity);
},
/**
* Update a record.
*/ async update (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!fp.isObject(body.data)) {
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).update(id, {
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Destroy a record.
*/ async delete (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
await strapi.service(uid).delete(id, sanitizedQuery);
ctx.status = 204;
}
};
};
exports.createCollectionTypeController = createCollectionTypeController;
//# sourceMappingURL=collection-type.js.map
@@ -0,0 +1 @@
{"version":3,"file":"collection-type.js","sources":["../../../src/core-api/controller/collection-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Core, Struct, Utils, UID } from '@strapi/types';\nimport type Koa from 'koa';\n\ninterface Options {\n contentType: Struct.CollectionTypeSchema;\n}\n\n/**\n *\n * Returns a collection type controller to handle default core-api actions\n */\nconst createCollectionTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.CollectionType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve records.\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const { results, pagination } = await strapi.service(uid).find(sanitizedQuery);\n const sanitizedResults = await this.sanitizeOutput(results, ctx);\n return this.transformResponse(sanitizedResults, { pagination });\n },\n\n /**\n * Retrieve a record\n */\n async findOne(ctx) {\n const { id } = ctx.params;\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).findOne(id, sanitizedQuery);\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * Create a record.\n */\n async create(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const { body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).create({\n ...sanitizedQuery,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n ctx.status = 201;\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * Update a record.\n */\n async update(ctx: Koa.Context) {\n const { id } = ctx.params;\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const { body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).update(id, {\n ...sanitizedQuery,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * Destroy a record.\n */\n async delete(ctx) {\n const { id } = ctx.params;\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n await strapi.service(uid).delete(id, sanitizedQuery);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createCollectionTypeController };\n"],"names":["createCollectionTypeController","contentType","uid","find","ctx","validateQuery","sanitizedQuery","sanitizeQuery","results","pagination","strapi","service","sanitizedResults","sanitizeOutput","transformResponse","findOne","id","params","entity","sanitizedEntity","create","body","request","isObject","data","errors","ValidationError","validateInput","sanitizedInputData","sanitizeInput","status","update","delete"],"mappings":";;;;;AASA;;;AAGC,IACKA,MAAAA,8BAAAA,GAAiC,CAAC,EACtCC,WAAW,EACH,GAAA;IACR,MAAMC,GAAAA,GAAMD,YAAYC,GAAG;;IAG3B,OAAO;AACL;;QAGA,MAAMC,MAAKC,GAAG,EAAA;YACZ,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;AAEhD,YAAA,MAAM,EAAEI,OAAO,EAAEC,UAAU,EAAE,GAAG,MAAMC,MAAAA,CAAOC,OAAO,CAACT,GAAKC,CAAAA,CAAAA,IAAI,CAACG,cAAAA,CAAAA;AAC/D,YAAA,MAAMM,mBAAmB,MAAM,IAAI,CAACC,cAAc,CAACL,OAASJ,EAAAA,GAAAA,CAAAA;AAC5D,YAAA,OAAO,IAAI,CAACU,iBAAiB,CAACF,gBAAkB,EAAA;AAAEH,gBAAAA;AAAW,aAAA,CAAA;AAC/D,SAAA;AAEA;;QAGA,MAAMM,SAAQX,GAAG,EAAA;AACf,YAAA,MAAM,EAAEY,EAAE,EAAE,GAAGZ,IAAIa,MAAM;YACzB,MAAM,IAAI,CAACZ,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;YAEhD,MAAMc,MAAAA,GAAS,MAAMR,MAAOC,CAAAA,OAAO,CAACT,GAAKa,CAAAA,CAAAA,OAAO,CAACC,EAAIV,EAAAA,cAAAA,CAAAA;AACrD,YAAA,MAAMa,kBAAkB,MAAM,IAAI,CAACN,cAAc,CAACK,MAAQd,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACU,iBAAiB,CAACK,eAAAA,CAAAA;AAChC,SAAA;AAEA;;QAGA,MAAMC,QAAOhB,GAAG,EAAA;YACd,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,Line truncated
@@ -0,0 +1,83 @@
import { isObject } from 'lodash/fp';
import { errors } from '@strapi/utils';
/**
*
* Returns a collection type controller to handle default core-api actions
*/ const createCollectionTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve records.
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { results, pagination } = await strapi.service(uid).find(sanitizedQuery);
const sanitizedResults = await this.sanitizeOutput(results, ctx);
return this.transformResponse(sanitizedResults, {
pagination
});
},
/**
* Retrieve a record
*/ async findOne (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).findOne(id, sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Create a record.
*/ async create (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!isObject(body.data)) {
throw new errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).create({
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
ctx.status = 201;
return this.transformResponse(sanitizedEntity);
},
/**
* Update a record.
*/ async update (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!isObject(body.data)) {
throw new errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).update(id, {
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Destroy a record.
*/ async delete (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
await strapi.service(uid).delete(id, sanitizedQuery);
ctx.status = 204;
}
};
};
export { createCollectionTypeController };
//# sourceMappingURL=collection-type.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"collection-type.mjs","sources":["../../../src/core-api/controller/collection-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Core, Struct, Utils, UID } from '@strapi/types';\nimport type Koa from 'koa';\n\ninterface Options {\n contentType: Struct.CollectionTypeSchema;\n}\n\n/**\n *\n * Returns a collection type controller to handle default core-api actions\n */\nconst createCollectionTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.CollectionType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve records.\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const { results, pagination } = await strapi.service(uid).find(sanitizedQuery);\n const sanitizedResults = await this.sanitizeOutput(results, ctx);\n return this.transformResponse(sanitizedResults, { pagination });\n },\n\n /**\n * Retrieve a record\n */\n async findOne(ctx) {\n const { id } = ctx.params;\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).findOne(id, sanitizedQuery);\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * Create a record.\n */\n async create(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const { body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).create({\n ...sanitizedQuery,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n ctx.status = 201;\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * Update a record.\n */\n async update(ctx: Koa.Context) {\n const { id } = ctx.params;\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const { body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).update(id, {\n ...sanitizedQuery,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * Destroy a record.\n */\n async delete(ctx) {\n const { id } = ctx.params;\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n await strapi.service(uid).delete(id, sanitizedQuery);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createCollectionTypeController };\n"],"names":["createCollectionTypeController","contentType","uid","find","ctx","validateQuery","sanitizedQuery","sanitizeQuery","results","pagination","strapi","service","sanitizedResults","sanitizeOutput","transformResponse","findOne","id","params","entity","sanitizedEntity","create","body","request","isObject","data","errors","ValidationError","validateInput","sanitizedInputData","sanitizeInput","status","update","delete"],"mappings":";;;AASA;;;AAGC,IACKA,MAAAA,8BAAAA,GAAiC,CAAC,EACtCC,WAAW,EACH,GAAA;IACR,MAAMC,GAAAA,GAAMD,YAAYC,GAAG;;IAG3B,OAAO;AACL;;QAGA,MAAMC,MAAKC,GAAG,EAAA;YACZ,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;AAEhD,YAAA,MAAM,EAAEI,OAAO,EAAEC,UAAU,EAAE,GAAG,MAAMC,MAAAA,CAAOC,OAAO,CAACT,GAAKC,CAAAA,CAAAA,IAAI,CAACG,cAAAA,CAAAA;AAC/D,YAAA,MAAMM,mBAAmB,MAAM,IAAI,CAACC,cAAc,CAACL,OAASJ,EAAAA,GAAAA,CAAAA;AAC5D,YAAA,OAAO,IAAI,CAACU,iBAAiB,CAACF,gBAAkB,EAAA;AAAEH,gBAAAA;AAAW,aAAA,CAAA;AAC/D,SAAA;AAEA;;QAGA,MAAMM,SAAQX,GAAG,EAAA;AACf,YAAA,MAAM,EAAEY,EAAE,EAAE,GAAGZ,IAAIa,MAAM;YACzB,MAAM,IAAI,CAACZ,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;YAEhD,MAAMc,MAAAA,GAAS,MAAMR,MAAOC,CAAAA,OAAO,CAACT,GAAKa,CAAAA,CAAAA,OAAO,CAACC,EAAIV,EAAAA,cAAAA,CAAAA;AACrD,YAAA,MAAMa,kBAAkB,MAAM,IAAI,CAACN,cAAc,CAACK,MAAQd,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACU,iBAAiB,CAACK,eAAAA,CAAAA;AAChC,SAAA;AAEA;;QAGA,MAAMC,QAAOhB,GAAG,EAAA;YACd,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,ILine truncated
+6
View File
@@ -0,0 +1,6 @@
import type { Core, Struct } from '@strapi/types';
declare function createController<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {
contentType: T;
}): T extends Struct.SingleTypeSchema ? Core.CoreAPI.Controller.SingleType : Core.CoreAPI.Controller.CollectionType;
export { createController };
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAalD,iBAAS,gBAAgB,CAAC,CAAC,SAAS,MAAM,CAAC,gBAAgB,GAAG,MAAM,CAAC,oBAAoB,EAAE,IAAI,EAAE;IAC/F,WAAW,EAAE,CAAC,CAAC;CAChB,GAAG,CAAC,SAAS,MAAM,CAAC,gBAAgB,GACjC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,GAClC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,cAAc,CAAC;AA2D3C,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
+67
View File
@@ -0,0 +1,67 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
var transform = require('./transform.js');
var singleType = require('./single-type.js');
var collectionType = require('./collection-type.js');
var requestContext = require('../../services/request-context.js');
const isSingleType = (contentType)=>strapiUtils.contentTypes.isSingleType(contentType);
const getAuthFromKoaContext = (ctx)=>fp.prop('state.auth', ctx) ?? {};
function createController({ contentType }) {
// TODO: replace with Base class + SingleType and CollectionType classes
const proto = {
transformResponse (data, meta) {
const ctx = requestContext.get();
return transform.transformResponse(data, meta, {
contentType,
useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4'
});
},
async sanitizeOutput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.output(data, contentType, {
auth
});
},
async sanitizeInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.input(data, contentType, {
auth
});
},
async sanitizeQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.query(ctx.query, contentType, {
auth
});
},
async validateQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.query(ctx.query, contentType, {
auth
});
},
async validateInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.input(data, contentType, {
auth
});
}
};
let ctrl;
if (isSingleType(contentType)) {
ctrl = singleType.createSingleTypeController({
contentType
});
} else {
ctrl = collectionType.createCollectionTypeController({
contentType
});
}
return Object.assign(Object.create(proto), ctrl);
}
exports.createController = createController;
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/core-api/controller/index.ts"],"sourcesContent":["import { prop } from 'lodash/fp';\nimport type Koa from 'koa';\nimport { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { transformResponse } from './transform';\nimport { createSingleTypeController } from './single-type';\nimport { createCollectionTypeController } from './collection-type';\nimport requestCtx from '../../services/request-context';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\nconst getAuthFromKoaContext = (ctx: Koa.Context) => prop('state.auth', ctx) ?? {};\n\nfunction createController<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Controller.SingleType\n : Core.CoreAPI.Controller.CollectionType;\nfunction createController({\n contentType,\n}: {\n contentType: Struct.SingleTypeSchema | Struct.CollectionTypeSchema;\n}) {\n // TODO: replace with Base class + SingleType and CollectionType classes\n\n const proto: Core.CoreAPI.Controller.Base = {\n transformResponse(data, meta) {\n const ctx = requestCtx.get();\n return transformResponse(data, meta, {\n contentType,\n useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4',\n });\n },\n\n async sanitizeOutput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.output(data, contentType, { auth });\n },\n\n async sanitizeInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.input(data, contentType, { auth });\n },\n\n async sanitizeQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.query(ctx.query, contentType, { auth });\n },\n\n async validateQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.query(ctx.query, contentType, { auth });\n },\n\n async validateInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.input(data, contentType, { auth });\n },\n };\n\n let ctrl;\n\n if (isSingleType(contentType)) {\n ctrl = createSingleTypeController({ contentType });\n } else {\n ctrl = createCollectionTypeController({ contentType });\n }\n\n return Object.assign(Object.create(proto), ctrl);\n}\n\nexport { createController };\n"],"names":["isSingleType","contentType","contentTypeUtils","getAuthFromKoaContext","ctx","prop","createController","proto","transformResponse","data","meta","requestCtx","get","useJsonAPIFormat","headers","sanitizeOutput","auth","strapi","contentAPI","sanitize","output","sanitizeInput","input","sanitizeQuery","query","validateQuery","validate","validateInput","ctrl","createSingleTypeController","createCollectionTypeController","Object","assign","create"],"mappings":";;;;;;;;;AAUA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,wBAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAE3E,MAAME,wBAAwB,CAACC,GAAAA,GAAqBC,OAAK,CAAA,YAAA,EAAcD,QAAQ,EAAC;AAOhF,SAASE,gBAAAA,CAAiB,EACxBL,WAAW,EAGZ,EAAA;;AAGC,IAAA,MAAMM,KAAsC,GAAA;QAC1CC,iBAAkBC,CAAAA,CAAAA,IAAI,EAAEC,IAAI,EAAA;YAC1B,MAAMN,GAAAA,GAAMO,eAAWC,GAAG,EAAA;YAC1B,OAAOJ,2BAAAA,CAAkBC,MAAMC,IAAM,EAAA;AACnCT,gBAAAA,WAAAA;AACAY,gBAAAA,gBAAAA,EAAkBT,GAAKU,EAAAA,OAAAA,GAAU,wBAAA,CAAyB,KAAK;AACjE,aAAA,CAAA;AACF,SAAA;QAEA,MAAMC,cAAAA,CAAAA,CAAeN,IAAI,EAAEL,GAAG,EAAA;AAC5B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACC,MAAM,CAACX,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACrE,SAAA;QAEA,MAAMK,aAAAA,CAAAA,CAAcZ,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACG,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE,SAAA;AAEA,QAAA,MAAMO,eAAcnB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACK,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;AAEA,QAAA,MAAMS,eAAcrB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACF,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;QAEA,MAAMW,aAAAA,CAAAA,CAAclB,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACJ,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE;AACF,KAAA;IAEA,IAAIY,IAAAA;AAEJ,IAAA,IAAI5B,aAAaC,WAAc,CAAA,EAAA;AAC7B2B,QAAAA,IAAAA,GAAOC,qCAA2B,CAAA;AAAE5B,YAAAA;AAAY,SAAA,CAAA;KAC3C,MAAA;AACL2B,QAAAA,IAAAA,GAAOE,6CAA+B,CAAA;AAAE7B,YAAAA;AAAY,SAAA,CAAA;AACtD;AAEA,IAAA,OAAO8B,OAAOC,MAAM,CAACD,MAAOE,CAAAA,MAAM,CAAC1B,KAAQqB,CAAAA,EAAAA,IAAAA,CAAAA;AAC7C;;;;"}
+65
View File
@@ -0,0 +1,65 @@
import { prop } from 'lodash/fp';
import { contentTypes } from '@strapi/utils';
import { transformResponse } from './transform.mjs';
import { createSingleTypeController } from './single-type.mjs';
import { createCollectionTypeController } from './collection-type.mjs';
import requestCtx from '../../services/request-context.mjs';
const isSingleType = (contentType)=>contentTypes.isSingleType(contentType);
const getAuthFromKoaContext = (ctx)=>prop('state.auth', ctx) ?? {};
function createController({ contentType }) {
// TODO: replace with Base class + SingleType and CollectionType classes
const proto = {
transformResponse (data, meta) {
const ctx = requestCtx.get();
return transformResponse(data, meta, {
contentType,
useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4'
});
},
async sanitizeOutput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.output(data, contentType, {
auth
});
},
async sanitizeInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.input(data, contentType, {
auth
});
},
async sanitizeQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.query(ctx.query, contentType, {
auth
});
},
async validateQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.query(ctx.query, contentType, {
auth
});
},
async validateInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.input(data, contentType, {
auth
});
}
};
let ctrl;
if (isSingleType(contentType)) {
ctrl = createSingleTypeController({
contentType
});
} else {
ctrl = createCollectionTypeController({
contentType
});
}
return Object.assign(Object.create(proto), ctrl);
}
export { createController };
//# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../src/core-api/controller/index.ts"],"sourcesContent":["import { prop } from 'lodash/fp';\nimport type Koa from 'koa';\nimport { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { transformResponse } from './transform';\nimport { createSingleTypeController } from './single-type';\nimport { createCollectionTypeController } from './collection-type';\nimport requestCtx from '../../services/request-context';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\nconst getAuthFromKoaContext = (ctx: Koa.Context) => prop('state.auth', ctx) ?? {};\n\nfunction createController<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Controller.SingleType\n : Core.CoreAPI.Controller.CollectionType;\nfunction createController({\n contentType,\n}: {\n contentType: Struct.SingleTypeSchema | Struct.CollectionTypeSchema;\n}) {\n // TODO: replace with Base class + SingleType and CollectionType classes\n\n const proto: Core.CoreAPI.Controller.Base = {\n transformResponse(data, meta) {\n const ctx = requestCtx.get();\n return transformResponse(data, meta, {\n contentType,\n useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4',\n });\n },\n\n async sanitizeOutput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.output(data, contentType, { auth });\n },\n\n async sanitizeInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.input(data, contentType, { auth });\n },\n\n async sanitizeQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.query(ctx.query, contentType, { auth });\n },\n\n async validateQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.query(ctx.query, contentType, { auth });\n },\n\n async validateInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.input(data, contentType, { auth });\n },\n };\n\n let ctrl;\n\n if (isSingleType(contentType)) {\n ctrl = createSingleTypeController({ contentType });\n } else {\n ctrl = createCollectionTypeController({ contentType });\n }\n\n return Object.assign(Object.create(proto), ctrl);\n}\n\nexport { createController };\n"],"names":["isSingleType","contentType","contentTypeUtils","getAuthFromKoaContext","ctx","prop","createController","proto","transformResponse","data","meta","requestCtx","get","useJsonAPIFormat","headers","sanitizeOutput","auth","strapi","contentAPI","sanitize","output","sanitizeInput","input","sanitizeQuery","query","validateQuery","validate","validateInput","ctrl","createSingleTypeController","createCollectionTypeController","Object","assign","create"],"mappings":";;;;;;;AAUA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,YAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAE3E,MAAME,wBAAwB,CAACC,GAAAA,GAAqBC,IAAK,CAAA,YAAA,EAAcD,QAAQ,EAAC;AAOhF,SAASE,gBAAAA,CAAiB,EACxBL,WAAW,EAGZ,EAAA;;AAGC,IAAA,MAAMM,KAAsC,GAAA;QAC1CC,iBAAkBC,CAAAA,CAAAA,IAAI,EAAEC,IAAI,EAAA;YAC1B,MAAMN,GAAAA,GAAMO,WAAWC,GAAG,EAAA;YAC1B,OAAOJ,iBAAAA,CAAkBC,MAAMC,IAAM,EAAA;AACnCT,gBAAAA,WAAAA;AACAY,gBAAAA,gBAAAA,EAAkBT,GAAKU,EAAAA,OAAAA,GAAU,wBAAA,CAAyB,KAAK;AACjE,aAAA,CAAA;AACF,SAAA;QAEA,MAAMC,cAAAA,CAAAA,CAAeN,IAAI,EAAEL,GAAG,EAAA;AAC5B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACC,MAAM,CAACX,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACrE,SAAA;QAEA,MAAMK,aAAAA,CAAAA,CAAcZ,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACG,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE,SAAA;AAEA,QAAA,MAAMO,eAAcnB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACK,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;AAEA,QAAA,MAAMS,eAAcrB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACF,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;QAEA,MAAMW,aAAAA,CAAAA,CAAclB,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACJ,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE;AACF,KAAA;IAEA,IAAIY,IAAAA;AAEJ,IAAA,IAAI5B,aAAaC,WAAc,CAAA,EAAA;AAC7B2B,QAAAA,IAAAA,GAAOC,0BAA2B,CAAA;AAAE5B,YAAAA;AAAY,SAAA,CAAA;KAC3C,MAAA;AACL2B,QAAAA,IAAAA,GAAOE,8BAA+B,CAAA;AAAE7B,YAAAA;AAAY,SAAA,CAAA;AACtD;AAEA,IAAA,OAAO8B,OAAOC,MAAM,CAACD,MAAOE,CAAAA,MAAM,CAAC1B,KAAQqB,CAAAA,EAAAA,IAAAA,CAAAA;AAC7C;;;;"}
@@ -0,0 +1,10 @@
import type { Struct, Core, Utils } from '@strapi/types';
interface Options {
contentType: Struct.SingleTypeSchema;
}
/**
* Returns a single type controller to handle default core-api actions
*/
declare const createSingleTypeController: ({ contentType, }: Options) => Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType>;
export { createSingleTypeController };
//# sourceMappingURL=single-type.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"single-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/single-type.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAO,MAAM,eAAe,CAAC;AAE9D,UAAU,OAAO;IACf,WAAW,EAAE,MAAM,CAAC,gBAAgB,CAAC;CACtC;AAED;;GAEG;AACH,QAAA,MAAM,0BAA0B,qBAE7B,OAAO,KAAG,MAAM,eAAe,CAAC,KAAK,OAAO,CAAC,UAAU,CAAC,UAAU,CAoDpE,CAAC;AAEF,OAAO,EAAE,0BAA0B,EAAE,CAAC"}
@@ -0,0 +1,47 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
/**
* Returns a single type controller to handle default core-api actions
*/ const createSingleTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve single type content
*
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).find(sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* create or update single type content.
*/ async update (ctx) {
const { query, body = {} } = ctx.request;
if (!fp.isObject(body.data)) {
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).createOrUpdate({
...query,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
async delete (ctx) {
const { query } = ctx;
await strapi.service(uid).delete(query);
ctx.status = 204;
}
};
};
exports.createSingleTypeController = createSingleTypeController;
//# sourceMappingURL=single-type.js.map
@@ -0,0 +1 @@
{"version":3,"file":"single-type.js","sources":["../../../src/core-api/controller/single-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Struct, Core, Utils, UID } from '@strapi/types';\n\ninterface Options {\n contentType: Struct.SingleTypeSchema;\n}\n\n/**\n * Returns a single type controller to handle default core-api actions\n */\nconst createSingleTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve single type content\n *\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).find(sanitizedQuery);\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * create or update single type content.\n */\n async update(ctx) {\n const { query, body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).createOrUpdate({\n ...query,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n async delete(ctx) {\n const { query } = ctx;\n\n await strapi.service(uid).delete(query);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createSingleTypeController };\n"],"names":["createSingleTypeController","contentType","uid","find","ctx","validateQuery","sanitizedQuery","sanitizeQuery","entity","strapi","service","sanitizedEntity","sanitizeOutput","transformResponse","update","query","body","request","isObject","data","errors","ValidationError","validateInput","sanitizedInputData","sanitizeInput","createOrUpdate","delete","status"],"mappings":";;;;;AAQA;;AAEC,IACKA,MAAAA,0BAAAA,GAA6B,CAAC,EAClCC,WAAW,EACH,GAAA;IACR,MAAMC,GAAAA,GAAMD,YAAYC,GAAG;;IAG3B,OAAO;AACL;;;QAIA,MAAMC,MAAKC,GAAG,EAAA;YACZ,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;AAEhD,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKC,IAAI,CAACG,cAAAA,CAAAA;AAE9C,YAAA,MAAMK,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA;;QAGA,MAAMG,QAAOV,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAEC,IAAAA,GAAO,EAAS,EAAE,GAAGZ,GAAAA,CAAIa,OAAO;AAE/C,YAAA,IAAI,CAACC,WAAAA,CAASF,IAAKG,CAAAA,IAAI,CAAG,EAAA;gBACxB,MAAM,IAAIC,kBAAOC,CAAAA,eAAe,CAAC,4CAAA,CAAA;AACnC;AAEA,YAAA,MAAM,IAAI,CAACC,aAAa,CAACN,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;YAEpC,MAAMmB,kBAAAA,GAAqB,MAAM,IAAI,CAACC,aAAa,CAACR,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;AAE/D,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKuB,cAAc,CAAC;AACtD,gBAAA,GAAGV,KAAK;gBACRI,IAAMI,EAAAA;AACR,aAAA,CAAA;AAEA,YAAA,MAAMZ,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA,QAAA,MAAMe,QAAOtB,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAE,GAAGX,GAAAA;AAElB,YAAA,MAAMK,MAAOC,CAAAA,OAAO,CAACR,GAAAA,CAAAA,CAAKwB,MAAM,CAACX,KAAAA,CAAAA;AAEjCX,YAAAA,GAAAA,CAAIuB,MAAM,GAAG,GAAA;AACf;AACF,KAAA;AACF;;;;"}
@@ -0,0 +1,45 @@
import { isObject } from 'lodash/fp';
import { errors } from '@strapi/utils';
/**
* Returns a single type controller to handle default core-api actions
*/ const createSingleTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve single type content
*
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).find(sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* create or update single type content.
*/ async update (ctx) {
const { query, body = {} } = ctx.request;
if (!isObject(body.data)) {
throw new errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).createOrUpdate({
...query,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
async delete (ctx) {
const { query } = ctx;
await strapi.service(uid).delete(query);
ctx.status = 204;
}
};
};
export { createSingleTypeController };
//# sourceMappingURL=single-type.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"single-type.mjs","sources":["../../../src/core-api/controller/single-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Struct, Core, Utils, UID } from '@strapi/types';\n\ninterface Options {\n contentType: Struct.SingleTypeSchema;\n}\n\n/**\n * Returns a single type controller to handle default core-api actions\n */\nconst createSingleTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve single type content\n *\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).find(sanitizedQuery);\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * create or update single type content.\n */\n async update(ctx) {\n const { query, body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).createOrUpdate({\n ...query,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n async delete(ctx) {\n const { query } = ctx;\n\n await strapi.service(uid).delete(query);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createSingleTypeController };\n"],"names":["createSingleTypeController","contentType","uid","find","ctx","validateQuery","sanitizedQuery","sanitizeQuery","entity","strapi","service","sanitizedEntity","sanitizeOutput","transformResponse","update","query","body","request","isObject","data","errors","ValidationError","validateInput","sanitizedInputData","sanitizeInput","createOrUpdate","delete","status"],"mappings":";;;AAQA;;AAEC,IACKA,MAAAA,0BAAAA,GAA6B,CAAC,EAClCC,WAAW,EACH,GAAA;IACR,MAAMC,GAAAA,GAAMD,YAAYC,GAAG;;IAG3B,OAAO;AACL;;;QAIA,MAAMC,MAAKC,GAAG,EAAA;YACZ,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;AAEhD,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKC,IAAI,CAACG,cAAAA,CAAAA;AAE9C,YAAA,MAAMK,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA;;QAGA,MAAMG,QAAOV,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAEC,IAAAA,GAAO,EAAS,EAAE,GAAGZ,GAAAA,CAAIa,OAAO;AAE/C,YAAA,IAAI,CAACC,QAAAA,CAASF,IAAKG,CAAAA,IAAI,CAAG,EAAA;gBACxB,MAAM,IAAIC,MAAOC,CAAAA,eAAe,CAAC,4CAAA,CAAA;AACnC;AAEA,YAAA,MAAM,IAAI,CAACC,aAAa,CAACN,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;YAEpC,MAAMmB,kBAAAA,GAAqB,MAAM,IAAI,CAACC,aAAa,CAACR,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;AAE/D,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKuB,cAAc,CAAC;AACtD,gBAAA,GAAGV,KAAK;gBACRI,IAAMI,EAAAA;AACR,aAAA,CAAA;AAEA,YAAA,MAAMZ,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA,QAAA,MAAMe,QAAOtB,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAE,GAAGX,GAAAA;AAElB,YAAA,MAAMK,MAAOC,CAAAA,OAAO,CAACR,GAAAA,CAAAA,CAAKwB,MAAM,CAACX,KAAAA,CAAAA;AAEjCX,YAAAA,GAAAA,CAAIuB,MAAM,GAAG,GAAA;AACf;AACF,KAAA;AACF;;;;"}
@@ -0,0 +1,14 @@
import type { Struct } from '@strapi/types';
interface TransformOptions {
contentType?: Struct.ContentTypeSchema | Struct.ComponentSchema;
/**
* @deprecated this option is deprecated and will be removed in the next major version
*/
useJsonAPIFormat?: boolean;
}
declare const transformResponse: (resource: any, meta?: unknown, opts?: TransformOptions) => {
data: any;
meta: unknown;
} | null | undefined;
export { transformResponse };
//# sourceMappingURL=transform.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"transform.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/transform.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAO,MAAM,EAAQ,MAAM,eAAe,CAAC;AA2BvD,UAAU,gBAAgB;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC,iBAAiB,GAAG,MAAM,CAAC,eAAe,CAAC;IAChE;;OAEG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,QAAA,MAAM,iBAAiB,aACX,GAAG,SACP,OAAO,SACP,gBAAgB;;;oBAgBvB,CAAC;AAkFF,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
+85
View File
@@ -0,0 +1,85 @@
'use strict';
var fp = require('lodash/fp');
function isEntry(property) {
return property === null || fp.isPlainObject(property) || Array.isArray(property);
}
function isDZEntries(property) {
return Array.isArray(property);
}
const transformResponse = (resource, meta = {}, opts = {
useJsonAPIFormat: false
})=>{
if (fp.isNil(resource)) {
return resource;
}
if (!fp.isPlainObject(resource) && !Array.isArray(resource)) {
throw new Error('Entry must be an object or an array of objects');
}
return {
data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,
meta
};
};
function transformComponent(data, component) {
if (Array.isArray(data)) {
return data.map((datum)=>transformComponent(datum, component));
}
const res = transformEntry(data, component);
if (fp.isNil(res)) {
return res;
}
const { id, attributes } = res;
return {
id,
...attributes
};
}
function transformEntry(entry, type) {
if (fp.isNil(entry)) {
return entry;
}
if (Array.isArray(entry)) {
return entry.map((singleEntry)=>transformEntry(singleEntry, type));
}
if (!fp.isPlainObject(entry)) {
throw new Error('Entry must be an object');
}
const { id, documentId, ...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 (fp.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,
documentId,
attributes: attributeValues
};
}
exports.transformResponse = transformResponse;
//# sourceMappingURL=transform.js.map
@@ -0,0 +1 @@
{"version":3,"file":"transform.js","sources":["../../../src/core-api/controller/transform.ts"],"sourcesContent":["import { isNil, isPlainObject } from 'lodash/fp';\nimport type { UID, Struct, Data } from '@strapi/types';\n\ntype TransformedEntry = {\n id: string;\n documentId?: Data.DocumentID | null;\n attributes: Record<string, unknown>;\n};\n\ntype TransformedComponent = {\n id: string;\n [key: string]: unknown;\n};\n\ntype Entry = {\n id: string;\n documentId: Data.DocumentID | null;\n [key: string]: Entry | Entry[] | string | number | null | boolean | Date;\n};\n\nfunction isEntry(property: unknown): property is Entry | Entry[] {\n return property === null || isPlainObject(property) || Array.isArray(property);\n}\n\nfunction isDZEntries(property: unknown): property is (Entry & { __component: UID.Component })[] {\n return Array.isArray(property);\n}\n\ninterface TransformOptions {\n contentType?: Struct.ContentTypeSchema | Struct.ComponentSchema;\n /**\n * @deprecated this option is deprecated and will be removed in the next major version\n */\n useJsonAPIFormat?: boolean;\n}\n\nconst transformResponse = (\n resource: any,\n meta: unknown = {},\n opts: TransformOptions = {\n useJsonAPIFormat: false,\n }\n) => {\n if (isNil(resource)) {\n return resource;\n }\n\n if (!isPlainObject(resource) && !Array.isArray(resource)) {\n throw new Error('Entry must be an object or an array of objects');\n }\n\n return {\n data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,\n meta,\n };\n};\n\nfunction transformComponent<T extends Entry | Entry[] | null>(\n data: T,\n component: Struct.ComponentSchema\n): T extends Entry[] ? TransformedComponent[] : T extends Entry ? TransformedComponent : null;\nfunction transformComponent(\n data: Entry | Entry[] | null,\n component: Struct.ComponentSchema\n): TransformedComponent | TransformedComponent[] | null {\n if (Array.isArray(data)) {\n return data.map((datum) => transformComponent(datum, component));\n }\n\n const res = transformEntry(data, component);\n\n if (isNil(res)) {\n return res;\n }\n\n const { id, attributes } = res;\n return { id, ...attributes };\n}\n\nfunction transformEntry<T extends Entry | Entry[] | null>(\n entry: T,\n type?: Struct.Schema\n): T extends Entry[] ? TransformedEntry[] : T extends Entry ? TransformedEntry : null;\nfunction transformEntry(\n entry: Entry | Entry[] | null,\n type?: Struct.Schema\n): TransformedEntry | TransformedEntry[] | null {\n if (isNil(entry)) {\n return entry;\n }\n\n if (Array.isArray(entry)) {\n return entry.map((singleEntry) => transformEntry(singleEntry, type));\n }\n\n if (!isPlainObject(entry)) {\n throw new Error('Entry must be an object');\n }\n\n const { id, documentId, ...properties } = entry;\n\n const attributeValues: Record<string, unknown> = {};\n\n for (const key of Object.keys(properties)) {\n const property = properties[key];\n const attribute = type && type.attributes[key];\n\n if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {\n const data = transformEntry(property, strapi.contentType(attribute.target));\n\n attributeValues[key] = { data };\n } else if (attribute && attribute.type === 'component' && isEntry(property)) {\n attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);\n } else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {\n if (isNil(property)) {\n attributeValues[key] = property;\n }\n\n attributeValues[key] = property.map((subProperty) => {\n return transformComponent(subProperty, strapi.components[subProperty.__component]);\n });\n } else if (attribute && attribute.type === 'media' && isEntry(property)) {\n const data = transformEntry(property, strapi.contentType('plugin::upload.file'));\n\n attributeValues[key] = { data };\n } else {\n attributeValues[key] = property;\n }\n }\n\n return {\n id,\n documentId,\n attributes: attributeValues,\n };\n}\n\nexport { transformResponse };\n"],"names":["isEntry","property","isPlainObject","Array","isArray","isDZEntries","transformResponse","resource","meta","opts","useJsonAPIFormat","isNil","Error","data","transformEntry","contentType","transformComponent","component","map","datum","res","id","attributes","entry","type","singleEntry","documentId","properties","attributeValues","key","Object","keys","attribute","strapi","target","components","subProperty","__component"],"mappings":";;;;AAoBA,SAASA,QAAQC,QAAiB,EAAA;AAChC,IAAA,OAAOA,aAAa,IAAQC,IAAAA,gBAAAA,CAAcD,QAAaE,CAAAA,IAAAA,KAAAA,CAAMC,OAAO,CAACH,QAAAA,CAAAA;AACvE;AAEA,SAASI,YAAYJ,QAAiB,EAAA;IACpC,OAAOE,KAAAA,CAAMC,OAAO,CAACH,QAAAA,CAAAA;AACvB;AAUA,MAAMK,oBAAoB,CACxBC,QAAAA,EACAC,OAAgB,EAAE,EAClBC,IAAyB,GAAA;IACvBC,gBAAkB,EAAA;AACpB,CAAC,GAAA;AAED,IAAA,IAAIC,SAAMJ,QAAW,CAAA,EAALine truncated
@@ -0,0 +1,83 @@
import { isNil, isPlainObject } from 'lodash/fp';
function isEntry(property) {
return property === null || isPlainObject(property) || Array.isArray(property);
}
function isDZEntries(property) {
return Array.isArray(property);
}
const transformResponse = (resource, meta = {}, opts = {
useJsonAPIFormat: false
})=>{
if (isNil(resource)) {
return resource;
}
if (!isPlainObject(resource) && !Array.isArray(resource)) {
throw new Error('Entry must be an object or an array of objects');
}
return {
data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,
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, documentId, ...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,
documentId,
attributes: attributeValues
};
}
export { transformResponse };
//# sourceMappingURL=transform.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"transform.mjs","sources":["../../../src/core-api/controller/transform.ts"],"sourcesContent":["import { isNil, isPlainObject } from 'lodash/fp';\nimport type { UID, Struct, Data } from '@strapi/types';\n\ntype TransformedEntry = {\n id: string;\n documentId?: Data.DocumentID | null;\n attributes: Record<string, unknown>;\n};\n\ntype TransformedComponent = {\n id: string;\n [key: string]: unknown;\n};\n\ntype Entry = {\n id: string;\n documentId: Data.DocumentID | null;\n [key: string]: Entry | Entry[] | string | number | null | boolean | Date;\n};\n\nfunction isEntry(property: unknown): property is Entry | Entry[] {\n return property === null || isPlainObject(property) || Array.isArray(property);\n}\n\nfunction isDZEntries(property: unknown): property is (Entry & { __component: UID.Component })[] {\n return Array.isArray(property);\n}\n\ninterface TransformOptions {\n contentType?: Struct.ContentTypeSchema | Struct.ComponentSchema;\n /**\n * @deprecated this option is deprecated and will be removed in the next major version\n */\n useJsonAPIFormat?: boolean;\n}\n\nconst transformResponse = (\n resource: any,\n meta: unknown = {},\n opts: TransformOptions = {\n useJsonAPIFormat: false,\n }\n) => {\n if (isNil(resource)) {\n return resource;\n }\n\n if (!isPlainObject(resource) && !Array.isArray(resource)) {\n throw new Error('Entry must be an object or an array of objects');\n }\n\n return {\n data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,\n meta,\n };\n};\n\nfunction transformComponent<T extends Entry | Entry[] | null>(\n data: T,\n component: Struct.ComponentSchema\n): T extends Entry[] ? TransformedComponent[] : T extends Entry ? TransformedComponent : null;\nfunction transformComponent(\n data: Entry | Entry[] | null,\n component: Struct.ComponentSchema\n): TransformedComponent | TransformedComponent[] | null {\n if (Array.isArray(data)) {\n return data.map((datum) => transformComponent(datum, component));\n }\n\n const res = transformEntry(data, component);\n\n if (isNil(res)) {\n return res;\n }\n\n const { id, attributes } = res;\n return { id, ...attributes };\n}\n\nfunction transformEntry<T extends Entry | Entry[] | null>(\n entry: T,\n type?: Struct.Schema\n): T extends Entry[] ? TransformedEntry[] : T extends Entry ? TransformedEntry : null;\nfunction transformEntry(\n entry: Entry | Entry[] | null,\n type?: Struct.Schema\n): TransformedEntry | TransformedEntry[] | null {\n if (isNil(entry)) {\n return entry;\n }\n\n if (Array.isArray(entry)) {\n return entry.map((singleEntry) => transformEntry(singleEntry, type));\n }\n\n if (!isPlainObject(entry)) {\n throw new Error('Entry must be an object');\n }\n\n const { id, documentId, ...properties } = entry;\n\n const attributeValues: Record<string, unknown> = {};\n\n for (const key of Object.keys(properties)) {\n const property = properties[key];\n const attribute = type && type.attributes[key];\n\n if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {\n const data = transformEntry(property, strapi.contentType(attribute.target));\n\n attributeValues[key] = { data };\n } else if (attribute && attribute.type === 'component' && isEntry(property)) {\n attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);\n } else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {\n if (isNil(property)) {\n attributeValues[key] = property;\n }\n\n attributeValues[key] = property.map((subProperty) => {\n return transformComponent(subProperty, strapi.components[subProperty.__component]);\n });\n } else if (attribute && attribute.type === 'media' && isEntry(property)) {\n const data = transformEntry(property, strapi.contentType('plugin::upload.file'));\n\n attributeValues[key] = { data };\n } else {\n attributeValues[key] = property;\n }\n }\n\n return {\n id,\n documentId,\n attributes: attributeValues,\n };\n}\n\nexport { transformResponse };\n"],"names":["isEntry","property","isPlainObject","Array","isArray","isDZEntries","transformResponse","resource","meta","opts","useJsonAPIFormat","isNil","Error","data","transformEntry","contentType","transformComponent","component","map","datum","res","id","attributes","entry","type","singleEntry","documentId","properties","attributeValues","key","Object","keys","attribute","strapi","target","components","subProperty","__component"],"mappings":";;AAoBA,SAASA,QAAQC,QAAiB,EAAA;AAChC,IAAA,OAAOA,aAAa,IAAQC,IAAAA,aAAAA,CAAcD,QAAaE,CAAAA,IAAAA,KAAAA,CAAMC,OAAO,CAACH,QAAAA,CAAAA;AACvE;AAEA,SAASI,YAAYJ,QAAiB,EAAA;IACpC,OAAOE,KAAAA,CAAMC,OAAO,CAACH,QAAAA,CAAAA;AACvB;AAUA,MAAMK,oBAAoB,CACxBC,QAAAA,EACAC,OAAgB,EAAE,EAClBC,IAAyB,GAAA;IACvBC,gBAAkB,EAAA;AACpB,CAAC,GAAA;AAED,IAAA,IAAIC,MAAMJ,QAAW,CAAA,EAAA;Line truncated
+24
View File
@@ -0,0 +1,24 @@
import type { Schema } from '@strapi/types';
export declare const createRoutes: ({ contentType }: {
contentType: Schema.ContentType;
}) => {
find: {
method: string;
path: string;
handler: string;
config: {};
};
update: {
method: string;
path: string;
handler: string;
config: {};
};
delete: {
method: string;
path: string;
handler: string;
config: {};
};
};
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core-api/routes/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAE5C,eAAO,MAAM,YAAY,oBAAqB;IAAE,WAAW,EAAE,OAAO,WAAW,CAAA;CAAE;;;;;;;;;;;;;;;;;;;CAMhF,CAAC"}
+69
View File
@@ -0,0 +1,69 @@
'use strict';
var strapiUtils = require('@strapi/utils');
const createRoutes = ({ contentType })=>{
if (strapiUtils.contentTypes.isSingleType(contentType)) {
return getSingleTypeRoutes(contentType);
}
return getCollectionTypeRoutes(contentType);
};
const getSingleTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.singularName}`,
handler: `${uid}.find`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.singularName}`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.singularName}`,
handler: `${uid}.delete`,
config: {}
}
};
};
const getCollectionTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.pluralName}`,
handler: `${uid}.find`,
config: {}
},
findOne: {
method: 'GET',
path: `/${info.pluralName}/:id`,
handler: `${uid}.findOne`,
config: {}
},
create: {
method: 'POST',
path: `/${info.pluralName}`,
handler: `${uid}.create`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.pluralName}/:id`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.pluralName}/:id`,
handler: `${uid}.delete`,
config: {}
}
};
};
exports.createRoutes = createRoutes;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/core-api/routes/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\n\nexport const createRoutes = ({ contentType }: { contentType: Schema.ContentType }) => {\n if (contentTypeUtils.isSingleType(contentType)) {\n return getSingleTypeRoutes(contentType);\n }\n\n return getCollectionTypeRoutes(contentType);\n};\n\nconst getSingleTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.singularName}`,\n handler: `${uid}.find`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.singularName}`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.singularName}`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n\nconst getCollectionTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.pluralName}`,\n handler: `${uid}.find`,\n config: {},\n },\n findOne: {\n method: 'GET',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.findOne`,\n config: {},\n },\n create: {\n method: 'POST',\n path: `/${info.pluralName}`,\n handler: `${uid}.create`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n"],"names":["createRoutes","contentType","contentTypeUtils","isSingleType","getSingleTypeRoutes","getCollectionTypeRoutes","uid","info","find","method","path","singularName","handler","config","update","delete","pluralName","findOne","create"],"mappings":";;;;AAGaA,MAAAA,YAAAA,GAAe,CAAC,EAAEC,WAAW,EAAuC,GAAA;IAC/E,IAAIC,wBAAAA,CAAiBC,YAAY,CAACF,WAAc,CAAA,EAAA;AAC9C,QAAA,OAAOG,mBAAoBH,CAAAA,WAAAA,CAAAA;AAC7B;AAEA,IAAA,OAAOI,uBAAwBJ,CAAAA,WAAAA,CAAAA;AACjC;AAEA,MAAMG,sBAAsB,CAAC,EAAEE,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAC5D,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;AAEA,MAAMR,0BAA0B,CAAC,EAAEC,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAChE,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAI,OAAS,EAAA;YACPR,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,QAAQ,CAAC;AACzBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAK,MAAQ,EAAA;YACNT,MAAQ,EAAA,MAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;;;;"}
+67
View File
@@ -0,0 +1,67 @@
import { contentTypes } from '@strapi/utils';
const createRoutes = ({ contentType })=>{
if (contentTypes.isSingleType(contentType)) {
return getSingleTypeRoutes(contentType);
}
return getCollectionTypeRoutes(contentType);
};
const getSingleTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.singularName}`,
handler: `${uid}.find`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.singularName}`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.singularName}`,
handler: `${uid}.delete`,
config: {}
}
};
};
const getCollectionTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.pluralName}`,
handler: `${uid}.find`,
config: {}
},
findOne: {
method: 'GET',
path: `/${info.pluralName}/:id`,
handler: `${uid}.findOne`,
config: {}
},
create: {
method: 'POST',
path: `/${info.pluralName}`,
handler: `${uid}.create`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.pluralName}/:id`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.pluralName}/:id`,
handler: `${uid}.delete`,
config: {}
}
};
};
export { createRoutes };
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../src/core-api/routes/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\n\nexport const createRoutes = ({ contentType }: { contentType: Schema.ContentType }) => {\n if (contentTypeUtils.isSingleType(contentType)) {\n return getSingleTypeRoutes(contentType);\n }\n\n return getCollectionTypeRoutes(contentType);\n};\n\nconst getSingleTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.singularName}`,\n handler: `${uid}.find`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.singularName}`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.singularName}`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n\nconst getCollectionTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.pluralName}`,\n handler: `${uid}.find`,\n config: {},\n },\n findOne: {\n method: 'GET',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.findOne`,\n config: {},\n },\n create: {\n method: 'POST',\n path: `/${info.pluralName}`,\n handler: `${uid}.create`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n"],"names":["createRoutes","contentType","contentTypeUtils","isSingleType","getSingleTypeRoutes","getCollectionTypeRoutes","uid","info","find","method","path","singularName","handler","config","update","delete","pluralName","findOne","create"],"mappings":";;AAGaA,MAAAA,YAAAA,GAAe,CAAC,EAAEC,WAAW,EAAuC,GAAA;IAC/E,IAAIC,YAAAA,CAAiBC,YAAY,CAACF,WAAc,CAAA,EAAA;AAC9C,QAAA,OAAOG,mBAAoBH,CAAAA,WAAAA,CAAAA;AAC7B;AAEA,IAAA,OAAOI,uBAAwBJ,CAAAA,WAAAA,CAAAA;AACjC;AAEA,MAAMG,sBAAsB,CAAC,EAAEE,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAC5D,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;AAEA,MAAMR,0BAA0B,CAAC,EAAEC,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAChE,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAI,OAAS,EAAA;YACPR,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,QAAQ,CAAC;AACzBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAK,MAAQ,EAAA;YACNT,MAAQ,EAAA,MAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;;;;"}
@@ -0,0 +1,27 @@
import type { Core, Struct, Modules } from '@strapi/types';
import { CoreService } from './core-service';
export declare class CollectionTypeService extends CoreService implements Core.CoreAPI.Service.CollectionType {
private contentType;
constructor(contentType: Struct.CollectionTypeSchema);
find(params?: {}): Promise<{
results: Modules.Documents.AnyDocument[];
pagination: import("@strapi/utils/dist/pagination").PagePatinationInformation | import("@strapi/utils/dist/pagination").OffsetPaginationInformation;
}>;
findOne(documentId: Modules.Documents.ID, params?: {}): import("@strapi/types/dist/modules/documents/result/document-engine").FindOne<import("@strapi/types/dist/uid").ContentType, any>;
create(params?: {
data: {};
}): Promise<Modules.Documents.AnyDocument>;
update(documentId: Modules.Documents.ID, params?: {
data: {};
}): import("@strapi/types/dist/modules/documents/result/document-engine").Update<import("@strapi/types/dist/uid").ContentType, any>;
delete(documentId: Modules.Documents.ID, params?: {}): Promise<{
deletedEntries: number;
}>;
}
/**
*
* Returns a collection type service to handle default core-api actions
*/
declare const createCollectionTypeService: (contentType: Struct.CollectionTypeSchema) => Core.CoreAPI.Service.CollectionType;
export { createCollectionTypeService };
//# sourceMappingURL=collection-type.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"collection-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/collection-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAS3D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,qBAAa,qBACX,SAAQ,WACR,YAAW,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc;IAE9C,OAAO,CAAC,WAAW,CAA8B;gBAErC,WAAW,EAAE,MAAM,CAAC,oBAAoB;IAM9C,IAAI,CAAC,MAAM,KAAK;;;;IAgCtB,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,KAAK;IAS/C,MAAM,CAAC,MAAM;;KAAe;IAMlC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM;;KAAe;IASxD,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,KAAK;;;CAU3D;AAED;;;GAGG;AAEH,QAAA,MAAM,2BAA2B,gBAClB,OAAO,oBAAoB,KACvC,KAAK,OAAO,CAAC,OAAO,CAAC,cAEvB,CAAC;AAEF,OAAO,EAAE,2BAA2B,EAAE,CAAC"}
@@ -0,0 +1,80 @@
'use strict';
var pagination = require('./pagination.js');
var coreService = require('./core-service.js');
class CollectionTypeService extends coreService.CoreService {
async find(params = {}) {
const { uid } = this.contentType;
const fetchParams = this.getFetchParams(params);
const paginationInfo = pagination.getPaginationInfo(fetchParams);
const isPaged = pagination.isPagedPagination(fetchParams.pagination);
const results = await strapi.documents(uid).findMany({
...fetchParams,
...paginationInfo
});
if (pagination.shouldCount(fetchParams)) {
const count = await strapi.documents(uid).count({
...fetchParams,
...paginationInfo
});
if (typeof count !== 'number') {
throw new Error('Count should be a number');
}
return {
results,
pagination: pagination.transformPaginationResponse(paginationInfo, count, isPaged)
};
}
return {
results,
pagination: pagination.transformPaginationResponse(paginationInfo, undefined, isPaged)
};
}
findOne(documentId, params = {}) {
const { uid } = this.contentType;
return strapi.documents(uid).findOne({
...this.getFetchParams(params),
documentId
});
}
async create(params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).create(this.getFetchParams(params));
}
update(documentId, params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).update({
...this.getFetchParams(params),
documentId
});
}
async delete(documentId, params = {}) {
const { uid } = this.contentType;
const { entries } = await strapi.documents(uid).delete({
...this.getFetchParams(params),
documentId
});
return {
deletedEntries: entries.length
};
}
constructor(contentType){
super();
this.contentType = contentType;
}
}
/**
*
* Returns a collection type service to handle default core-api actions
*/ const createCollectionTypeService = (contentType)=>{
return new CollectionTypeService(contentType);
};
exports.CollectionTypeService = CollectionTypeService;
exports.createCollectionTypeService = createCollectionTypeService;
//# sourceMappingURL=collection-type.js.map
@@ -0,0 +1 @@
{"version":3,"file":"collection-type.js","sources":["../../../src/core-api/service/collection-type.ts"],"sourcesContent":["import type { Core, Struct, Modules } from '@strapi/types';\n\nimport {\n getPaginationInfo,\n shouldCount,\n isPagedPagination,\n transformPaginationResponse,\n} from './pagination';\n\nimport { CoreService } from './core-service';\n\nexport class CollectionTypeService\n extends CoreService\n implements Core.CoreAPI.Service.CollectionType\n{\n private contentType: Struct.CollectionTypeSchema;\n\n constructor(contentType: Struct.CollectionTypeSchema) {\n super();\n\n this.contentType = contentType;\n }\n\n async find(params = {}) {\n const { uid } = this.contentType;\n\n const fetchParams = this.getFetchParams(params);\n\n const paginationInfo = getPaginationInfo(fetchParams);\n const isPaged = isPagedPagination(fetchParams.pagination);\n\n const results = await strapi.documents(uid).findMany({\n ...fetchParams,\n ...paginationInfo,\n });\n\n if (shouldCount(fetchParams)) {\n const count = await strapi.documents(uid).count({ ...fetchParams, ...paginationInfo });\n\n if (typeof count !== 'number') {\n throw new Error('Count should be a number');\n }\n\n return {\n results,\n pagination: transformPaginationResponse(paginationInfo, count, isPaged),\n };\n }\n\n return {\n results,\n pagination: transformPaginationResponse(paginationInfo, undefined, isPaged),\n };\n }\n\n findOne(documentId: Modules.Documents.ID, params = {}) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).findOne({\n ...this.getFetchParams(params),\n documentId,\n });\n }\n\n async create(params = { data: {} }) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).create(this.getFetchParams(params));\n }\n\n update(documentId: Modules.Documents.ID, params = { data: {} }) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).update({\n ...this.getFetchParams(params),\n documentId,\n });\n }\n\n async delete(documentId: Modules.Documents.ID, params = {}) {\n const { uid } = this.contentType;\n\n const { entries } = await strapi.documents(uid).delete({\n ...this.getFetchParams(params),\n documentId,\n });\n\n return { deletedEntries: entries.length };\n }\n}\n\n/**\n *\n * Returns a collection type service to handle default core-api actions\n */\n\nconst createCollectionTypeService = (\n contentType: Struct.CollectionTypeSchema\n): Core.CoreAPI.Service.CollectionType => {\n return new CollectionTypeService(contentType);\n};\n\nexport { createCollectionTypeService };\n"],"names":["CollectionTypeService","CoreService","find","params","uid","contentType","fetchParams","getFetchParams","paginationInfo","getPaginationInfo","isPaged","isPagedPagination","pagination","results","strapi","documents","findMany","shouldCount","count","Error","transformPaginationResponse","undefined","findOne","documentId","create","data","update","delete","entries","deletedEntries","length","constructor","createCollectionTypeService"],"mappings":";;;;;AAWO,MAAMA,qBACHC,SAAAA,uBAAAA,CAAAA;AAWR,IAAA,MAAMC,IAAKC,CAAAA,MAAAA,GAAS,EAAE,EAAE;AACtB,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,MAAMC,WAAc,GAAA,IAAI,CAACC,cAAc,CAACJ,MAAAA,CAAAA;AAExC,QAAA,MAAMK,iBAAiBC,4BAAkBH,CAAAA,WAAAA,CAAAA;QACzC,MAAMI,OAAAA,GAAUC,4BAAkBL,CAAAA,WAAAA,CAAYM,UAAU,CAAA;AAExD,QAAA,MAAMC,UAAU,MAAMC,MAAAA,CAAOC,SAAS,CAACX,GAAAA,CAAAA,CAAKY,QAAQ,CAAC;AACnD,YAAA,GAAGV,WAAW;AACd,YAAA,GAAGE;AACL,SAAA,CAAA;AAEA,QAAA,IAAIS,uBAAYX,WAAc,CAAA,EAAA;AAC5B,YAAA,MAAMY,QAAQ,MAAMJ,MAAAA,CAAOC,SAAS,CAACX,GAAAA,CAAAA,CAAKc,KAAK,CAAC;AAAE,gBAAA,GAAGZ,WAAW;AAAE,gBAAA,GAAGE;AAAe,aAAA,CAAA;YAEpF,IAAI,OAAOU,UAAU,QAAU,EAAA;AAC7B,gBAAA,MAAM,IAAIC,KAAM,CAAA,0BAAA,CAAA;AAClB;YAEA,OAAO;AACLN,gBAAAA,OAAAA;gBACAD,UAAYQ,EAAAA,sCAAAA,CAA4BZ,gBAAgBU,KAAOR,EAAAA,OAAAA;AACjE,aAAA;AACF;QAEA,OAAO;AACLG,YAAAA,OAAAA;YACAD,UAAYQ,EAAAA,sCAAAA,CAA4BZ,gBAAgBa,SAAWX,EAAAA,OAAAA;AACrE,SAAA;AACF;AAEAY,IAAAA,OAAAA,CAAQC,UAAgC,EAAEpB,MAAS,GAAA,EAAE,EAAE;AACrD,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,OAAOS,MAAOC,CAAAA,SAAS,CAACX,GAAAA,CAAAA,CAAKkB,OAAO,CAAC;AACnC,YAAA,GAAG,IAAI,CAACf,cAAc,CAACJ,MAAO,CAAA;AAC9BoB,YAAAA;AACF,SAAA,CAAA;AACF;AAEA,IAAA,MAAMC,OAAOrB,MAAS,GAAA;AAAEsB,QAAAA,IAAAA,EAAM;AAAG,KAAC,EAAE;AAClC,QAAA,MAAM,EAAErB,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;QAEhC,OAAOS,MAAAA,CAAOC,SAAS,CAACX,GAAAA,CAAAA,CAAKoB,MAAM,CAAC,IAAI,CAACjB,cAAc,CAACJ,MAAAA,CAAAA,CAAAA;AAC1D;IAEAuB,MAAOH,CAAAA,UAAgC,EAAEpB,MAAS,GAAA;AAAEsB,QAAAA,IAAAA,EAAM;AAAG,KAAC,EAAE;AAC9D,QAAA,MAAM,EAAErB,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,OAAOS,MAAOC,CAAAA,SAAS,CAACX,GAAAA,CAAAA,CAAKsB,MAAM,CAAC;AAClC,YAAA,GAAG,IAAI,CAACnB,cAAc,CAACJ,MAAO,CAAA;AAC9BoB,YAAAA;AACF,SAAA,CAAA;AACF;AAEA,IAAA,MAAMI,OAAOJ,UAAgC,EAAEpB,MAAS,GAAA,EAAE,EAAE;AAC1D,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAWLine truncated
@@ -0,0 +1,77 @@
import { getPaginationInfo, isPagedPagination, shouldCount, transformPaginationResponse } from './pagination.mjs';
import { CoreService } from './core-service.mjs';
class CollectionTypeService extends CoreService {
async find(params = {}) {
const { uid } = this.contentType;
const fetchParams = this.getFetchParams(params);
const paginationInfo = getPaginationInfo(fetchParams);
const isPaged = isPagedPagination(fetchParams.pagination);
const results = await strapi.documents(uid).findMany({
...fetchParams,
...paginationInfo
});
if (shouldCount(fetchParams)) {
const count = await strapi.documents(uid).count({
...fetchParams,
...paginationInfo
});
if (typeof count !== 'number') {
throw new Error('Count should be a number');
}
return {
results,
pagination: transformPaginationResponse(paginationInfo, count, isPaged)
};
}
return {
results,
pagination: transformPaginationResponse(paginationInfo, undefined, isPaged)
};
}
findOne(documentId, params = {}) {
const { uid } = this.contentType;
return strapi.documents(uid).findOne({
...this.getFetchParams(params),
documentId
});
}
async create(params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).create(this.getFetchParams(params));
}
update(documentId, params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).update({
...this.getFetchParams(params),
documentId
});
}
async delete(documentId, params = {}) {
const { uid } = this.contentType;
const { entries } = await strapi.documents(uid).delete({
...this.getFetchParams(params),
documentId
});
return {
deletedEntries: entries.length
};
}
constructor(contentType){
super();
this.contentType = contentType;
}
}
/**
*
* Returns a collection type service to handle default core-api actions
*/ const createCollectionTypeService = (contentType)=>{
return new CollectionTypeService(contentType);
};
export { CollectionTypeService, createCollectionTypeService };
//# sourceMappingURL=collection-type.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"collection-type.mjs","sources":["../../../src/core-api/service/collection-type.ts"],"sourcesContent":["import type { Core, Struct, Modules } from '@strapi/types';\n\nimport {\n getPaginationInfo,\n shouldCount,\n isPagedPagination,\n transformPaginationResponse,\n} from './pagination';\n\nimport { CoreService } from './core-service';\n\nexport class CollectionTypeService\n extends CoreService\n implements Core.CoreAPI.Service.CollectionType\n{\n private contentType: Struct.CollectionTypeSchema;\n\n constructor(contentType: Struct.CollectionTypeSchema) {\n super();\n\n this.contentType = contentType;\n }\n\n async find(params = {}) {\n const { uid } = this.contentType;\n\n const fetchParams = this.getFetchParams(params);\n\n const paginationInfo = getPaginationInfo(fetchParams);\n const isPaged = isPagedPagination(fetchParams.pagination);\n\n const results = await strapi.documents(uid).findMany({\n ...fetchParams,\n ...paginationInfo,\n });\n\n if (shouldCount(fetchParams)) {\n const count = await strapi.documents(uid).count({ ...fetchParams, ...paginationInfo });\n\n if (typeof count !== 'number') {\n throw new Error('Count should be a number');\n }\n\n return {\n results,\n pagination: transformPaginationResponse(paginationInfo, count, isPaged),\n };\n }\n\n return {\n results,\n pagination: transformPaginationResponse(paginationInfo, undefined, isPaged),\n };\n }\n\n findOne(documentId: Modules.Documents.ID, params = {}) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).findOne({\n ...this.getFetchParams(params),\n documentId,\n });\n }\n\n async create(params = { data: {} }) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).create(this.getFetchParams(params));\n }\n\n update(documentId: Modules.Documents.ID, params = { data: {} }) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).update({\n ...this.getFetchParams(params),\n documentId,\n });\n }\n\n async delete(documentId: Modules.Documents.ID, params = {}) {\n const { uid } = this.contentType;\n\n const { entries } = await strapi.documents(uid).delete({\n ...this.getFetchParams(params),\n documentId,\n });\n\n return { deletedEntries: entries.length };\n }\n}\n\n/**\n *\n * Returns a collection type service to handle default core-api actions\n */\n\nconst createCollectionTypeService = (\n contentType: Struct.CollectionTypeSchema\n): Core.CoreAPI.Service.CollectionType => {\n return new CollectionTypeService(contentType);\n};\n\nexport { createCollectionTypeService };\n"],"names":["CollectionTypeService","CoreService","find","params","uid","contentType","fetchParams","getFetchParams","paginationInfo","getPaginationInfo","isPaged","isPagedPagination","pagination","results","strapi","documents","findMany","shouldCount","count","Error","transformPaginationResponse","undefined","findOne","documentId","create","data","update","delete","entries","deletedEntries","length","constructor","createCollectionTypeService"],"mappings":";;;AAWO,MAAMA,qBACHC,SAAAA,WAAAA,CAAAA;AAWR,IAAA,MAAMC,IAAKC,CAAAA,MAAAA,GAAS,EAAE,EAAE;AACtB,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,MAAMC,WAAc,GAAA,IAAI,CAACC,cAAc,CAACJ,MAAAA,CAAAA;AAExC,QAAA,MAAMK,iBAAiBC,iBAAkBH,CAAAA,WAAAA,CAAAA;QACzC,MAAMI,OAAAA,GAAUC,iBAAkBL,CAAAA,WAAAA,CAAYM,UAAU,CAAA;AAExD,QAAA,MAAMC,UAAU,MAAMC,MAAAA,CAAOC,SAAS,CAACX,GAAAA,CAAAA,CAAKY,QAAQ,CAAC;AACnD,YAAA,GAAGV,WAAW;AACd,YAAA,GAAGE;AACL,SAAA,CAAA;AAEA,QAAA,IAAIS,YAAYX,WAAc,CAAA,EAAA;AAC5B,YAAA,MAAMY,QAAQ,MAAMJ,MAAAA,CAAOC,SAAS,CAACX,GAAAA,CAAAA,CAAKc,KAAK,CAAC;AAAE,gBAAA,GAAGZ,WAAW;AAAE,gBAAA,GAAGE;AAAe,aAAA,CAAA;YAEpF,IAAI,OAAOU,UAAU,QAAU,EAAA;AAC7B,gBAAA,MAAM,IAAIC,KAAM,CAAA,0BAAA,CAAA;AAClB;YAEA,OAAO;AACLN,gBAAAA,OAAAA;gBACAD,UAAYQ,EAAAA,2BAAAA,CAA4BZ,gBAAgBU,KAAOR,EAAAA,OAAAA;AACjE,aAAA;AACF;QAEA,OAAO;AACLG,YAAAA,OAAAA;YACAD,UAAYQ,EAAAA,2BAAAA,CAA4BZ,gBAAgBa,SAAWX,EAAAA,OAAAA;AACrE,SAAA;AACF;AAEAY,IAAAA,OAAAA,CAAQC,UAAgC,EAAEpB,MAAS,GAAA,EAAE,EAAE;AACrD,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,OAAOS,MAAOC,CAAAA,SAAS,CAACX,GAAAA,CAAAA,CAAKkB,OAAO,CAAC;AACnC,YAAA,GAAG,IAAI,CAACf,cAAc,CAACJ,MAAO,CAAA;AAC9BoB,YAAAA;AACF,SAAA,CAAA;AACF;AAEA,IAAA,MAAMC,OAAOrB,MAAS,GAAA;AAAEsB,QAAAA,IAAAA,EAAM;AAAG,KAAC,EAAE;AAClC,QAAA,MAAM,EAAErB,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;QAEhC,OAAOS,MAAAA,CAAOC,SAAS,CAACX,GAAAA,CAAAA,CAAKoB,MAAM,CAAC,IAAI,CAACjB,cAAc,CAACJ,MAAAA,CAAAA,CAAAA;AAC1D;IAEAuB,MAAOH,CAAAA,UAAgC,EAAEpB,MAAS,GAAA;AAAEsB,QAAAA,IAAAA,EAAM;AAAG,KAAC,EAAE;AAC9D,QAAA,MAAM,EAAErB,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,OAAOS,MAAOC,CAAAA,SAAS,CAACX,GAAAA,CAAAA,CAAKsB,MAAM,CAAC;AAClC,YAAA,GAAG,IAAI,CAACnB,cAAc,CAACJ,MAAO,CAAA;AAC9BoB,YAAAA;AACF,SAAA,CAAA;AACF;AAEA,IAAA,MAAMI,OAAOJ,UAAgC,EAAEpB,MAAS,GAAA,EAAE,EAAE;AAC1D,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;QALine truncated
@@ -0,0 +1,4 @@
export declare abstract class CoreService {
getFetchParams(params?: {}): any;
}
//# sourceMappingURL=core-service.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"core-service.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/core-service.ts"],"names":[],"mappings":"AAAA,8BAAsB,WAAW;IAC/B,cAAc,CAAC,MAAM,KAAK,GAAG,GAAG;CAMjC"}
+13
View File
@@ -0,0 +1,13 @@
'use strict';
class CoreService {
getFetchParams(params = {}) {
return {
status: 'published',
...params
};
}
}
exports.CoreService = CoreService;
//# sourceMappingURL=core-service.js.map
@@ -0,0 +1 @@
{"version":3,"file":"core-service.js","sources":["../../../src/core-api/service/core-service.ts"],"sourcesContent":["export abstract class CoreService {\n getFetchParams(params = {}): any {\n return {\n status: 'published',\n ...params,\n };\n }\n}\n"],"names":["CoreService","getFetchParams","params","status"],"mappings":";;AAAO,MAAeA,WAAAA,CAAAA;IACpBC,cAAeC,CAAAA,MAAAA,GAAS,EAAE,EAAO;QAC/B,OAAO;YACLC,MAAQ,EAAA,WAAA;AACR,YAAA,GAAGD;AACL,SAAA;AACF;AACF;;;;"}
@@ -0,0 +1,11 @@
class CoreService {
getFetchParams(params = {}) {
return {
status: 'published',
...params
};
}
}
export { CoreService };
//# sourceMappingURL=core-service.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"core-service.mjs","sources":["../../../src/core-api/service/core-service.ts"],"sourcesContent":["export abstract class CoreService {\n getFetchParams(params = {}): any {\n return {\n status: 'published',\n ...params,\n };\n }\n}\n"],"names":["CoreService","getFetchParams","params","status"],"mappings":"AAAO,MAAeA,WAAAA,CAAAA;IACpBC,cAAeC,CAAAA,MAAAA,GAAS,EAAE,EAAO;QAC/B,OAAO;YACLC,MAAQ,EAAA,WAAA;AACR,YAAA,GAAGD;AACL,SAAA;AACF;AACF;;;;"}
+9
View File
@@ -0,0 +1,9 @@
import type { Core, Struct } from '@strapi/types';
/**
* Returns a core api for the provided model
*/
declare function createService<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {
contentType: T;
}): T extends Struct.SingleTypeSchema ? Core.CoreAPI.Service.SingleType : Core.CoreAPI.Service.CollectionType;
export { createService };
//# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AASlD;;GAEG;AACH,iBAAS,aAAa,CAAC,CAAC,SAAS,MAAM,CAAC,gBAAgB,GAAG,MAAM,CAAC,oBAAoB,EAAE,IAAI,EAAE;IAC5F,WAAW,EAAE,CAAC,CAAC;CAChB,GAAG,CAAC,SAAS,MAAM,CAAC,gBAAgB,GACjC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,GAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC;AAaxC,OAAO,EAAE,aAAa,EAAE,CAAC"}
+16
View File
@@ -0,0 +1,16 @@
'use strict';
var strapiUtils = require('@strapi/utils');
var singleType = require('./single-type.js');
var collectionType = require('./collection-type.js');
const isSingleType = (contentType)=>strapiUtils.contentTypes.isSingleType(contentType);
function createService({ contentType }) {
if (isSingleType(contentType)) {
return singleType.createSingleTypeService(contentType);
}
return collectionType.createCollectionTypeService(contentType);
}
exports.createService = createService;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/core-api/service/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { createSingleTypeService } from './single-type';\nimport { createCollectionTypeService } from './collection-type';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\n/**\n * Returns a core api for the provided model\n */\nfunction createService<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Service.SingleType\n : Core.CoreAPI.Service.CollectionType;\nfunction createService({\n contentType,\n}: {\n contentType: Struct.CollectionTypeSchema | Struct.SingleTypeSchema;\n}): Core.CoreAPI.Service.SingleType | Core.CoreAPI.Service.CollectionType {\n if (isSingleType(contentType)) {\n return createSingleTypeService(contentType);\n }\n\n return createCollectionTypeService(contentType);\n}\n\nexport { createService };\n"],"names":["isSingleType","contentType","contentTypeUtils","createService","createSingleTypeService","createCollectionTypeService"],"mappings":";;;;;;AAMA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,wBAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAU3E,SAASE,aAAAA,CAAc,EACrBF,WAAW,EAGZ,EAAA;AACC,IAAA,IAAID,aAAaC,WAAc,CAAA,EAAA;AAC7B,QAAA,OAAOG,kCAAwBH,CAAAA,WAAAA,CAAAA;AACjC;AAEA,IAAA,OAAOI,0CAA4BJ,CAAAA,WAAAA,CAAAA;AACrC;;;;"}
+14
View File
@@ -0,0 +1,14 @@
import { contentTypes } from '@strapi/utils';
import { createSingleTypeService } from './single-type.mjs';
import { createCollectionTypeService } from './collection-type.mjs';
const isSingleType = (contentType)=>contentTypes.isSingleType(contentType);
function createService({ contentType }) {
if (isSingleType(contentType)) {
return createSingleTypeService(contentType);
}
return createCollectionTypeService(contentType);
}
export { createService };
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../src/core-api/service/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { createSingleTypeService } from './single-type';\nimport { createCollectionTypeService } from './collection-type';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\n/**\n * Returns a core api for the provided model\n */\nfunction createService<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Service.SingleType\n : Core.CoreAPI.Service.CollectionType;\nfunction createService({\n contentType,\n}: {\n contentType: Struct.CollectionTypeSchema | Struct.SingleTypeSchema;\n}): Core.CoreAPI.Service.SingleType | Core.CoreAPI.Service.CollectionType {\n if (isSingleType(contentType)) {\n return createSingleTypeService(contentType);\n }\n\n return createCollectionTypeService(contentType);\n}\n\nexport { createService };\n"],"names":["isSingleType","contentType","contentTypeUtils","createService","createSingleTypeService","createCollectionTypeService"],"mappings":";;;;AAMA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,YAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAU3E,SAASE,aAAAA,CAAc,EACrBF,WAAW,EAGZ,EAAA;AACC,IAAA,IAAID,aAAaC,WAAc,CAAA,EAAA;AAC7B,QAAA,OAAOG,uBAAwBH,CAAAA,WAAAA,CAAAA;AACjC;AAEA,IAAA,OAAOI,2BAA4BJ,CAAAA,WAAAA,CAAAA;AACrC;;;;"}
+30
View File
@@ -0,0 +1,30 @@
import { pagination } from '@strapi/utils';
interface BasePaginationParams {
withCount?: boolean | 't' | '1' | 'true' | 'f' | '0' | 'false' | 0 | 1;
}
type PagedPagination = BasePaginationParams & {
page?: number;
pageSize?: number;
};
type OffsetPagination = BasePaginationParams & {
start?: number;
limit?: number;
};
export type PaginationParams = PagedPagination | OffsetPagination;
type PaginationInfo = {
page: number;
pageSize: number;
} | {
start: number;
limit: number;
};
declare const isPagedPagination: (pagination?: PaginationParams) => pagination is PagedPagination;
declare const shouldCount: (params: {
pagination?: PaginationParams;
}) => boolean;
declare const getPaginationInfo: (params: {
pagination?: PaginationParams;
}) => PaginationInfo;
declare const transformPaginationResponse: (paginationInfo: PaginationInfo, total: number | undefined, isPaged: boolean) => pagination.PagePatinationInformation | pagination.OffsetPaginationInformation;
export { isPagedPagination, shouldCount, getPaginationInfo, transformPaginationResponse };
//# sourceMappingURL=pagination.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/pagination.ts"],"names":[],"mappings":"AAEA,OAAO,EAAU,UAAU,EAAE,MAAM,eAAe,CAAC;AAEnD,UAAU,oBAAoB;IAC5B,SAAS,CAAC,EAAE,OAAO,GAAG,GAAG,GAAG,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;CACxE;AAED,KAAK,eAAe,GAAG,oBAAoB,GAAG;IAC5C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,KAAK,gBAAgB,GAAG,oBAAoB,GAAG;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,eAAe,GAAG,gBAAgB,CAAC;AAElE,KAAK,cAAc,GACf;IACE,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB,GACD;IACE,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAaN,QAAA,MAAM,iBAAiB,gBAAiB,gBAAgB,kCACmC,CAAC;AAE5F,QAAA,MAAM,WAAW,WAAY;IAAE,UAAU,CAAC,EAAE,gBAAgB,CAAA;CAAE,YA0B7D,CAAC;AAEF,QAAA,MAAM,iBAAiB,WAAY;IAAE,UAAU,CAAC,EAAE,gBAAgB,CAAA;CAAE,KAAG,cAStE,CAAC;AAEF,QAAA,MAAM,2BAA2B,mBACf,cAAc,SACvB,MAAM,GAAG,SAAS,WAChB,OAAO,kFAcjB,CAAC;AAEF,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,iBAAiB,EAAE,2BAA2B,EAAE,CAAC"}
+78
View File
@@ -0,0 +1,78 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
/**
* Default limit values from config
*/ const getLimitConfigDefaults = ()=>({
defaultLimit: fp.toNumber(strapi.config.get('api.rest.defaultLimit', 25)),
maxLimit: fp.toNumber(strapi.config.get('api.rest.maxLimit')) || null
});
const isOffsetPagination = (pagination)=>fp.has('start', pagination) || fp.has('limit', pagination);
const isPagedPagination = (pagination)=>fp.has('page', pagination) || fp.has('pageSize', pagination) || !isOffsetPagination(pagination);
const shouldCount = (params)=>{
if (fp.has('pagination.withCount', params)) {
const withCount = params.pagination?.withCount;
if (typeof withCount === 'boolean') {
return withCount;
}
if (typeof withCount === 'undefined') {
return false;
}
if ([
'true',
't',
'1',
1
].includes(withCount)) {
return true;
}
if ([
'false',
'f',
'0',
0
].includes(withCount)) {
return false;
}
throw new strapiUtils.errors.ValidationError('Invalid withCount parameter. Expected "t","1","true","false","0","f"');
}
return Boolean(strapi.config.get('api.rest.withCount', true));
};
const getPaginationInfo = (params)=>{
const { defaultLimit, maxLimit } = getLimitConfigDefaults();
const { start, limit } = strapiUtils.pagination.withDefaultPagination(params.pagination || {}, {
defaults: {
offset: {
limit: defaultLimit
},
page: {
pageSize: defaultLimit
}
},
maxLimit: maxLimit || -1
});
return {
start,
limit
};
};
const transformPaginationResponse = (paginationInfo, total, isPaged)=>{
const transform = isPaged ? strapiUtils.pagination.transformPagedPaginationInfo : strapiUtils.pagination.transformOffsetPaginationInfo;
const paginationResponse = transform(paginationInfo, total);
if (fp.isNil(total)) {
// Ignore total and pageCount if `total` value is not available.
return fp.omit([
'total',
'pageCount'
], paginationResponse);
}
return paginationResponse;
};
exports.getPaginationInfo = getPaginationInfo;
exports.isPagedPagination = isPagedPagination;
exports.shouldCount = shouldCount;
exports.transformPaginationResponse = transformPaginationResponse;
//# sourceMappingURL=pagination.js.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.js","sources":["../../../src/core-api/service/pagination.ts"],"sourcesContent":["import { omit, has, toNumber, isNil } from 'lodash/fp';\n\nimport { errors, pagination } from '@strapi/utils';\n\ninterface BasePaginationParams {\n withCount?: boolean | 't' | '1' | 'true' | 'f' | '0' | 'false' | 0 | 1;\n}\n\ntype PagedPagination = BasePaginationParams & {\n page?: number;\n pageSize?: number;\n};\n\ntype OffsetPagination = BasePaginationParams & {\n start?: number;\n limit?: number;\n};\n\nexport type PaginationParams = PagedPagination | OffsetPagination;\n\ntype PaginationInfo =\n | {\n page: number;\n pageSize: number;\n }\n | {\n start: number;\n limit: number;\n };\n\n/**\n * Default limit values from config\n */\nconst getLimitConfigDefaults = () => ({\n defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),\n maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null,\n});\n\nconst isOffsetPagination = (pagination?: PaginationParams): pagination is OffsetPagination =>\n has('start', pagination) || has('limit', pagination);\n\nconst isPagedPagination = (pagination?: PaginationParams): pagination is PagedPagination =>\n has('page', pagination) || has('pageSize', pagination) || !isOffsetPagination(pagination);\n\nconst shouldCount = (params: { pagination?: PaginationParams }) => {\n if (has('pagination.withCount', params)) {\n const withCount = params.pagination?.withCount;\n\n if (typeof withCount === 'boolean') {\n return withCount;\n }\n\n if (typeof withCount === 'undefined') {\n return false;\n }\n\n if (['true', 't', '1', 1].includes(withCount)) {\n return true;\n }\n\n if (['false', 'f', '0', 0].includes(withCount)) {\n return false;\n }\n\n throw new errors.ValidationError(\n 'Invalid withCount parameter. Expected \"t\",\"1\",\"true\",\"false\",\"0\",\"f\"'\n );\n }\n\n return Boolean(strapi.config.get('api.rest.withCount', true));\n};\n\nconst getPaginationInfo = (params: { pagination?: PaginationParams }): PaginationInfo => {\n const { defaultLimit, maxLimit } = getLimitConfigDefaults();\n\n const { start, limit } = pagination.withDefaultPagination(params.pagination || {}, {\n defaults: { offset: { limit: defaultLimit }, page: { pageSize: defaultLimit } },\n maxLimit: maxLimit || -1,\n });\n\n return { start, limit };\n};\n\nconst transformPaginationResponse = (\n paginationInfo: PaginationInfo,\n total: number | undefined,\n isPaged: boolean\n) => {\n const transform = isPaged\n ? pagination.transformPagedPaginationInfo\n : pagination.transformOffsetPaginationInfo;\n\n const paginationResponse = transform(paginationInfo, total!);\n\n if (isNil(total)) {\n // Ignore total and pageCount if `total` value is not available.\n return omit(['total', 'pageCount'], paginationResponse) as ReturnType<typeof transform>;\n }\n\n return paginationResponse;\n};\n\nexport { isPagedPagination, shouldCount, getPaginationInfo, transformPaginationResponse };\n"],"names":["getLimitConfigDefaults","defaultLimit","toNumber","strapi","config","get","maxLimit","isOffsetPagination","pagination","has","isPagedPagination","shouldCount","params","withCount","includes","errors","ValidationError","Boolean","getPaginationInfo","start","limit","withDefaultPagination","defaults","offset","page","pageSize","transformPaginationResponse","paginationInfo","total","isPaged","transform","transformPagedPaginationInfo","transformOffsetPaginationInfo","paginationResponse","isNil","omit"],"mappings":";;;;;AA8BA;;IAGA,MAAMA,sBAAyB,GAAA,KAAO;AACpCC,QAAAA,YAAAA,EAAcC,YAASC,MAAOC,CAAAA,MAAM,CAACC,GAAG,CAAC,uBAAyB,EAAA,EAAA,CAAA,CAAA;AAClEC,QAAAA,QAAAA,EAAUJ,YAASC,MAAOC,CAAAA,MAAM,CAACC,GAAG,CAAC,mBAAyB,CAAA,CAAA,IAAA;KAChE,CAAA;AAEA,MAAME,qBAAqB,CAACC,UAAAA,GAC1BC,OAAI,OAASD,EAAAA,UAAAA,CAAAA,IAAeC,OAAI,OAASD,EAAAA,UAAAA,CAAAA;AAErCE,MAAAA,iBAAAA,GAAoB,CAACF,UAAAA,GACzBC,MAAI,CAAA,MAAA,EAAQD,eAAeC,MAAI,CAAA,UAAA,EAAYD,UAAe,CAAA,IAAA,CAACD,kBAAmBC,CAAAA,UAAAA;AAEhF,MAAMG,cAAc,CAACC,MAAAA,GAAAA;IACnB,IAAIH,MAAAA,CAAI,wBAAwBG,MAAS,CAAA,EAAA;QACvC,MAAMC,SAAAA,GAAYD,MAAOJ,CAAAA,UAAU,EAAEK,SAAAA;QAErC,IAAI,OAAOA,cAAc,SAAW,EAAA;YAClC,OAAOA,SAAAA;AACT;QAEA,IAAI,OAAOA,cAAc,WAAa,EAAA;YACpC,OAAO,KAAA;AACT;QAEA,IAAI;AAAC,YAAA,MAAA;AAAQ,YAAA,GAAA;AAAK,YAAA,GAAA;AAAK,YAAA;SAAE,CAACC,QAAQ,CAACD,SAAY,CAAA,EAAA;YAC7C,OAAO,IAAA;AACT;QAEA,IAAI;AAAC,YAAA,OAAA;AAAS,YAAA,GAAA;AAAK,YAAA,GAAA;AAAK,YAAA;SAAE,CAACC,QAAQ,CAACD,SAAY,CAAA,EAAA;YAC9C,OAAO,KAAA;AACT;QAEA,MAAM,IAAIE,kBAAOC,CAAAA,eAAe,CAC9B,sEAAA,CAAA;AAEJ;AAEA,IAAA,OAAOC,QAAQd,MAAOC,CAAAA,MAAM,CAACC,GAAG,CAAC,oBAAsB,EAAA,IAAA,CAAA,CAAA;AACzD;AAEA,MAAMa,oBAAoB,CAACN,MAAAA,GAAAA;AACzB,IAAA,MAAM,EAAEX,YAAY,EAAEK,QAAQ,EAAE,GAAGN,sBAAAA,EAAAA;AAEnC,IAAA,MAAM,EAAEmB,KAAK,EAAEC,KAAK,EAAE,GAAGZ,sBAAWa,CAAAA,qBAAqB,CAACT,MAAAA,CAAOJ,UAAU,IAAI,EAAI,EAAA;QACjFc,QAAU,EAAA;YAAEC,MAAQ,EAAA;gBAAEH,KAAOnB,EAAAA;AAAa,aAAA;YAAGuB,IAAM,EAAA;gBLine truncated
+73
View File
@@ -0,0 +1,73 @@
import { has, isNil, omit, toNumber } from 'lodash/fp';
import { errors, pagination } from '@strapi/utils';
/**
* Default limit values from config
*/ const getLimitConfigDefaults = ()=>({
defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),
maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null
});
const isOffsetPagination = (pagination)=>has('start', pagination) || has('limit', pagination);
const isPagedPagination = (pagination)=>has('page', pagination) || has('pageSize', pagination) || !isOffsetPagination(pagination);
const shouldCount = (params)=>{
if (has('pagination.withCount', params)) {
const withCount = params.pagination?.withCount;
if (typeof withCount === 'boolean') {
return withCount;
}
if (typeof withCount === 'undefined') {
return false;
}
if ([
'true',
't',
'1',
1
].includes(withCount)) {
return true;
}
if ([
'false',
'f',
'0',
0
].includes(withCount)) {
return false;
}
throw new errors.ValidationError('Invalid withCount parameter. Expected "t","1","true","false","0","f"');
}
return Boolean(strapi.config.get('api.rest.withCount', true));
};
const getPaginationInfo = (params)=>{
const { defaultLimit, maxLimit } = getLimitConfigDefaults();
const { start, limit } = pagination.withDefaultPagination(params.pagination || {}, {
defaults: {
offset: {
limit: defaultLimit
},
page: {
pageSize: defaultLimit
}
},
maxLimit: maxLimit || -1
});
return {
start,
limit
};
};
const transformPaginationResponse = (paginationInfo, total, isPaged)=>{
const transform = isPaged ? pagination.transformPagedPaginationInfo : pagination.transformOffsetPaginationInfo;
const paginationResponse = transform(paginationInfo, total);
if (isNil(total)) {
// Ignore total and pageCount if `total` value is not available.
return omit([
'total',
'pageCount'
], paginationResponse);
}
return paginationResponse;
};
export { getPaginationInfo, isPagedPagination, shouldCount, transformPaginationResponse };
//# sourceMappingURL=pagination.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"pagination.mjs","sources":["../../../src/core-api/service/pagination.ts"],"sourcesContent":["import { omit, has, toNumber, isNil } from 'lodash/fp';\n\nimport { errors, pagination } from '@strapi/utils';\n\ninterface BasePaginationParams {\n withCount?: boolean | 't' | '1' | 'true' | 'f' | '0' | 'false' | 0 | 1;\n}\n\ntype PagedPagination = BasePaginationParams & {\n page?: number;\n pageSize?: number;\n};\n\ntype OffsetPagination = BasePaginationParams & {\n start?: number;\n limit?: number;\n};\n\nexport type PaginationParams = PagedPagination | OffsetPagination;\n\ntype PaginationInfo =\n | {\n page: number;\n pageSize: number;\n }\n | {\n start: number;\n limit: number;\n };\n\n/**\n * Default limit values from config\n */\nconst getLimitConfigDefaults = () => ({\n defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),\n maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null,\n});\n\nconst isOffsetPagination = (pagination?: PaginationParams): pagination is OffsetPagination =>\n has('start', pagination) || has('limit', pagination);\n\nconst isPagedPagination = (pagination?: PaginationParams): pagination is PagedPagination =>\n has('page', pagination) || has('pageSize', pagination) || !isOffsetPagination(pagination);\n\nconst shouldCount = (params: { pagination?: PaginationParams }) => {\n if (has('pagination.withCount', params)) {\n const withCount = params.pagination?.withCount;\n\n if (typeof withCount === 'boolean') {\n return withCount;\n }\n\n if (typeof withCount === 'undefined') {\n return false;\n }\n\n if (['true', 't', '1', 1].includes(withCount)) {\n return true;\n }\n\n if (['false', 'f', '0', 0].includes(withCount)) {\n return false;\n }\n\n throw new errors.ValidationError(\n 'Invalid withCount parameter. Expected \"t\",\"1\",\"true\",\"false\",\"0\",\"f\"'\n );\n }\n\n return Boolean(strapi.config.get('api.rest.withCount', true));\n};\n\nconst getPaginationInfo = (params: { pagination?: PaginationParams }): PaginationInfo => {\n const { defaultLimit, maxLimit } = getLimitConfigDefaults();\n\n const { start, limit } = pagination.withDefaultPagination(params.pagination || {}, {\n defaults: { offset: { limit: defaultLimit }, page: { pageSize: defaultLimit } },\n maxLimit: maxLimit || -1,\n });\n\n return { start, limit };\n};\n\nconst transformPaginationResponse = (\n paginationInfo: PaginationInfo,\n total: number | undefined,\n isPaged: boolean\n) => {\n const transform = isPaged\n ? pagination.transformPagedPaginationInfo\n : pagination.transformOffsetPaginationInfo;\n\n const paginationResponse = transform(paginationInfo, total!);\n\n if (isNil(total)) {\n // Ignore total and pageCount if `total` value is not available.\n return omit(['total', 'pageCount'], paginationResponse) as ReturnType<typeof transform>;\n }\n\n return paginationResponse;\n};\n\nexport { isPagedPagination, shouldCount, getPaginationInfo, transformPaginationResponse };\n"],"names":["getLimitConfigDefaults","defaultLimit","toNumber","strapi","config","get","maxLimit","isOffsetPagination","pagination","has","isPagedPagination","shouldCount","params","withCount","includes","errors","ValidationError","Boolean","getPaginationInfo","start","limit","withDefaultPagination","defaults","offset","page","pageSize","transformPaginationResponse","paginationInfo","total","isPaged","transform","transformPagedPaginationInfo","transformOffsetPaginationInfo","paginationResponse","isNil","omit"],"mappings":";;;AA8BA;;IAGA,MAAMA,sBAAyB,GAAA,KAAO;AACpCC,QAAAA,YAAAA,EAAcC,SAASC,MAAOC,CAAAA,MAAM,CAACC,GAAG,CAAC,uBAAyB,EAAA,EAAA,CAAA,CAAA;AAClEC,QAAAA,QAAAA,EAAUJ,SAASC,MAAOC,CAAAA,MAAM,CAACC,GAAG,CAAC,mBAAyB,CAAA,CAAA,IAAA;KAChE,CAAA;AAEA,MAAME,qBAAqB,CAACC,UAAAA,GAC1BC,IAAI,OAASD,EAAAA,UAAAA,CAAAA,IAAeC,IAAI,OAASD,EAAAA,UAAAA,CAAAA;AAErCE,MAAAA,iBAAAA,GAAoB,CAACF,UAAAA,GACzBC,GAAI,CAAA,MAAA,EAAQD,eAAeC,GAAI,CAAA,UAAA,EAAYD,UAAe,CAAA,IAAA,CAACD,kBAAmBC,CAAAA,UAAAA;AAEhF,MAAMG,cAAc,CAACC,MAAAA,GAAAA;IACnB,IAAIH,GAAAA,CAAI,wBAAwBG,MAAS,CAAA,EAAA;QACvC,MAAMC,SAAAA,GAAYD,MAAOJ,CAAAA,UAAU,EAAEK,SAAAA;QAErC,IAAI,OAAOA,cAAc,SAAW,EAAA;YAClC,OAAOA,SAAAA;AACT;QAEA,IAAI,OAAOA,cAAc,WAAa,EAAA;YACpC,OAAO,KAAA;AACT;QAEA,IAAI;AAAC,YAAA,MAAA;AAAQ,YAAA,GAAA;AAAK,YAAA,GAAA;AAAK,YAAA;SAAE,CAACC,QAAQ,CAACD,SAAY,CAAA,EAAA;YAC7C,OAAO,IAAA;AACT;QAEA,IAAI;AAAC,YAAA,OAAA;AAAS,YAAA,GAAA;AAAK,YAAA,GAAA;AAAK,YAAA;SAAE,CAACC,QAAQ,CAACD,SAAY,CAAA,EAAA;YAC9C,OAAO,KAAA;AACT;QAEA,MAAM,IAAIE,MAAOC,CAAAA,eAAe,CAC9B,sEAAA,CAAA;AAEJ;AAEA,IAAA,OAAOC,QAAQd,MAAOC,CAAAA,MAAM,CAACC,GAAG,CAAC,oBAAsB,EAAA,IAAA,CAAA,CAAA;AACzD;AAEA,MAAMa,oBAAoB,CAACN,MAAAA,GAAAA;AACzB,IAAA,MAAM,EAAEX,YAAY,EAAEK,QAAQ,EAAE,GAAGN,sBAAAA,EAAAA;AAEnC,IAAA,MAAM,EAAEmB,KAAK,EAAEC,KAAK,EAAE,GAAGZ,UAAWa,CAAAA,qBAAqB,CAACT,MAAAA,CAAOJ,UAAU,IAAI,EAAI,EAAA;QACjFc,QAAU,EAAA;YAAEC,MAAQ,EAAA;gBAAEH,KAAOnB,EAAAA;AAAa,aAAA;YAAGuB,IAAM,EAAA;gBAAELine truncated
@@ -0,0 +1,15 @@
import type { Struct, Core } from '@strapi/types';
import { CoreService } from './core-service';
export declare class SingleTypeService extends CoreService implements Core.CoreAPI.Service.SingleType {
private contentType;
constructor(contentType: Struct.SingleTypeSchema);
getDocumentId(): Promise<string>;
find(params?: {}): Promise<import("@strapi/types/dist/modules/documents").AnyDocument | null>;
createOrUpdate(params?: {}): Promise<import("@strapi/types/dist/modules/documents").AnyDocument | null>;
delete(params?: {}): Promise<{
deletedEntries: number;
}>;
}
declare const createSingleTypeService: (contentType: Struct.SingleTypeSchema) => Core.CoreAPI.Service.SingleType;
export { createSingleTypeService };
//# sourceMappingURL=single-type.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"single-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/single-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,qBAAa,iBAAkB,SAAQ,WAAY,YAAW,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU;IAC3F,OAAO,CAAC,WAAW,CAA0B;gBAEjC,WAAW,EAAE,MAAM,CAAC,gBAAgB;IAM1C,aAAa;IASb,IAAI,CAAC,MAAM,KAAK;IAMhB,cAAc,CAAC,MAAM,KAAK;IAe1B,MAAM,CAAC,MAAM,KAAK;;;CAazB;AAED,QAAA,MAAM,uBAAuB,gBACd,OAAO,gBAAgB,KACnC,KAAK,OAAO,CAAC,OAAO,CAAC,UAEvB,CAAC;AAEF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
+50
View File
@@ -0,0 +1,50 @@
'use strict';
var coreService = require('./core-service.js');
class SingleTypeService extends coreService.CoreService {
async getDocumentId() {
const { uid } = this.contentType;
return strapi.db.query(uid).findOne().then((document)=>document?.documentId);
}
async find(params = {}) {
const { uid } = this.contentType;
return strapi.documents(uid).findFirst(this.getFetchParams(params));
}
async createOrUpdate(params = {}) {
const { uid } = this.contentType;
const documentId = await this.getDocumentId();
if (documentId) {
return strapi.documents(uid).update({
...this.getFetchParams(params),
documentId
});
}
return strapi.documents(uid).create(this.getFetchParams(params));
}
async delete(params = {}) {
const { uid } = this.contentType;
const documentId = await this.getDocumentId();
if (!documentId) return {
deletedEntries: 0
};
const { entries } = await strapi.documents(uid).delete({
...this.getFetchParams(params),
documentId
});
return {
deletedEntries: entries.length
};
}
constructor(contentType){
super();
this.contentType = contentType;
}
}
const createSingleTypeService = (contentType)=>{
return new SingleTypeService(contentType);
};
exports.SingleTypeService = SingleTypeService;
exports.createSingleTypeService = createSingleTypeService;
//# sourceMappingURL=single-type.js.map
@@ -0,0 +1 @@
{"version":3,"file":"single-type.js","sources":["../../../src/core-api/service/single-type.ts"],"sourcesContent":["import type { Struct, Core } from '@strapi/types';\nimport { CoreService } from './core-service';\n\nexport class SingleTypeService extends CoreService implements Core.CoreAPI.Service.SingleType {\n private contentType: Struct.SingleTypeSchema;\n\n constructor(contentType: Struct.SingleTypeSchema) {\n super();\n\n this.contentType = contentType;\n }\n\n async getDocumentId() {\n const { uid } = this.contentType;\n\n return strapi.db\n .query(uid)\n .findOne()\n .then((document) => document?.documentId as string);\n }\n\n async find(params = {}) {\n const { uid } = this.contentType;\n\n return strapi.documents(uid).findFirst(this.getFetchParams(params));\n }\n\n async createOrUpdate(params = {}) {\n const { uid } = this.contentType;\n\n const documentId = await this.getDocumentId();\n\n if (documentId) {\n return strapi.documents(uid).update({\n ...this.getFetchParams(params),\n documentId,\n });\n }\n\n return strapi.documents(uid).create(this.getFetchParams(params));\n }\n\n async delete(params = {}) {\n const { uid } = this.contentType;\n\n const documentId = await this.getDocumentId();\n if (!documentId) return { deletedEntries: 0 };\n\n const { entries } = await strapi.documents(uid).delete({\n ...this.getFetchParams(params),\n documentId,\n });\n\n return { deletedEntries: entries.length };\n }\n}\n\nconst createSingleTypeService = (\n contentType: Struct.SingleTypeSchema\n): Core.CoreAPI.Service.SingleType => {\n return new SingleTypeService(contentType);\n};\n\nexport { createSingleTypeService };\n"],"names":["SingleTypeService","CoreService","getDocumentId","uid","contentType","strapi","db","query","findOne","then","document","documentId","find","params","documents","findFirst","getFetchParams","createOrUpdate","update","create","delete","deletedEntries","entries","length","constructor","createSingleTypeService"],"mappings":";;;;AAGO,MAAMA,iBAA0BC,SAAAA,uBAAAA,CAAAA;AASrC,IAAA,MAAMC,aAAgB,GAAA;AACpB,QAAA,MAAM,EAAEC,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,OAAOC,MAAOC,CAAAA,EAAE,CACbC,KAAK,CAACJ,GAAAA,CAAAA,CACNK,OAAO,EAAA,CACPC,IAAI,CAAC,CAACC,QAAAA,GAAaA,QAAUC,EAAAA,UAAAA,CAAAA;AAClC;AAEA,IAAA,MAAMC,IAAKC,CAAAA,MAAAA,GAAS,EAAE,EAAE;AACtB,QAAA,MAAM,EAAEV,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;QAEhC,OAAOC,MAAAA,CAAOS,SAAS,CAACX,GAAAA,CAAAA,CAAKY,SAAS,CAAC,IAAI,CAACC,cAAc,CAACH,MAAAA,CAAAA,CAAAA;AAC7D;AAEA,IAAA,MAAMI,cAAeJ,CAAAA,MAAAA,GAAS,EAAE,EAAE;AAChC,QAAA,MAAM,EAAEV,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,MAAMO,UAAa,GAAA,MAAM,IAAI,CAACT,aAAa,EAAA;AAE3C,QAAA,IAAIS,UAAY,EAAA;AACd,YAAA,OAAON,MAAOS,CAAAA,SAAS,CAACX,GAAAA,CAAAA,CAAKe,MAAM,CAAC;AAClC,gBAAA,GAAG,IAAI,CAACF,cAAc,CAACH,MAAO,CAAA;AAC9BF,gBAAAA;AACF,aAAA,CAAA;AACF;QAEA,OAAON,MAAAA,CAAOS,SAAS,CAACX,GAAAA,CAAAA,CAAKgB,MAAM,CAAC,IAAI,CAACH,cAAc,CAACH,MAAAA,CAAAA,CAAAA;AAC1D;AAEA,IAAA,MAAMO,MAAOP,CAAAA,MAAAA,GAAS,EAAE,EAAE;AACxB,QAAA,MAAM,EAAEV,GAAG,EAAE,GAAG,IAAI,CAACC,WAAW;AAEhC,QAAA,MAAMO,UAAa,GAAA,MAAM,IAAI,CAACT,aAAa,EAAA;QAC3C,IAAI,CAACS,YAAY,OAAO;YAAEU,cAAgB,EAAA;AAAE,SAAA;QAE5C,MAAM,EAAEC,OAAO,EAAE,GAAG,MAAMjB,OAAOS,SAAS,CAACX,GAAKiB,CAAAA,CAAAA,MAAM,CAAC;AACrD,YAAA,GAAG,IAAI,CAACJ,cAAc,CAACH,MAAO,CAAA;AAC9BF,YAAAA;AACF,SAAA,CAAA;QAEA,OAAO;AAAEU,YAAAA,cAAAA,EAAgBC,QAAQC;AAAO,SAAA;AAC1C;AAhDAC,IAAAA,WAAAA,CAAYpB,WAAoC,CAAE;QAChD,KAAK,EAAA;QAEL,IAAI,CAACA,WAAW,GAAGA,WAAAA;AACrB;AA6CF;AAEA,MAAMqB,0BAA0B,CAC9BrB,WAAAA,GAAAA;AAEA,IAAA,OAAO,IAAIJ,iBAAkBI,CAAAA,WAAAA,CAAAA;AAC/B;;;;;"}
Loaded 100 of 65041 files, more files were not shown because too many files have changed in this diff. Show more