@sclt/program-seed
Version:
Seed data
232 lines (187 loc) • 6.35 kB
JavaScript
const Faker = require('faker');
const inquirer = require('inquirer');
const { hello } = require('@sclt/utils-ui');
const { start, succeed } = require('@sclt/utils-spinner');
const pkg = require('./package');
(async function () {
hello(pkg);
const DEFAULT_API_URL = 'http://localhost:1337';
const Strapi = require('./lib');
const data = {};
const { API_URL, email, password, quantity } = await inquirer.prompt([
{
type: 'input',
name: 'API_URL',
message: 'Strapi API URL',
default: DEFAULT_API_URL,
},
{
type: 'input',
name: 'email',
message: 'Admin email address',
},
{
type: 'password',
name: 'password',
message: 'Admin password',
},
{
type: 'number',
name: 'quantity',
message: 'Number of entries',
},
]);
Strapi.configure(API_URL);
start('Authentification');
await Strapi.auth(email, password);
start('Fetch content types and groups');
let content_types = await Strapi.getContentTypes();
let groups = await Strapi.getGroups();
// do not create data for the following content types
content_types = content_types.filter((content_type) => {
return !['file', 'permission', 'role', 'administrator'].includes(content_type.uid);
});
// generate the entry object based on the content type attributes
function generateData(attributes) {
const match = {
string: Faker.lorem.words,
text: Faker.lorem.paragraphs,
richtext: Faker.lorem.paragraphs,
integer: Faker.random.number,
biginteger: Faker.random.number,
float: Faker.random.number,
decimal: Faker.random.number,
password: () => 'strapi',
date: () => Faker.date[Faker.random.boolean ? 'past' : 'future'](),
boolean: Faker.random.boolean,
json: () => {
return {
ok: true,
};
},
uuid: Faker.random.uuid,
email: Faker.internet.email,
};
const fieldsTogenerate = {};
Object.keys(attributes).forEach((attribute) => {
const definition = attributes[attribute];
if (attribute === 'id' || ['timestamp', 'relation', 'media'].includes(definition.type)) {
return;
}
if (definition.type === 'enumeration') {
fieldsTogenerate[attribute] =
definition.enum[Faker.random.number(definition.enum.length - 1)];
} else if (definition.type === 'group') {
if (definition.repeatable) {
fieldsTogenerate[attribute] = [];
for (let index = 0; index < Faker.random.number(3); index++) {
fieldsTogenerate[attribute].push(
generateData(groups.find((group) => group.uid === definition.group).schema.attributes)
);
}
} else {
fieldsTogenerate[attribute] = generateData(
groups.find((group) => group.uid === definition.group).schema.attributes
);
}
} else {
if (!match[definition.type]) {
console.log(`This type '${definition.type}' is not managed`);
}
fieldsTogenerate[attribute] = match[definition.type]();
}
});
return fieldsTogenerate;
}
// process create an entry
async function dataCreation(content_type) {
let entry = generateData(content_type.schema.attributes);
try {
entry = await Strapi.createEntry(content_type.uid, content_type.source || undefined, entry);
} catch (error) {
return;
}
if (!data[content_type.uid]) {
data[content_type.uid] = [];
}
data[content_type.uid].push(entry);
}
// process create all entries for a content type
async function contentTypeDataCreation(content_type) {
const dataCreationQueu = [];
for (let index = 0; index < quantity; index++) {
dataCreationQueu.push(dataCreation(content_type));
}
await Promise.all(dataCreationQueu);
}
const contentTypeDataCreationQueu = [];
content_types.forEach((content_type) => {
contentTypeDataCreationQueu.push(contentTypeDataCreation(content_type));
});
start('Create content types data');
await Promise.all(contentTypeDataCreationQueu);
// process update an enty to add relations
async function dataUpdate(entry, content_type) {
try {
entry = await Strapi.getEntry(content_type.uid, entry.id, content_type.source || undefined);
} catch (error) {
return;
}
Object.keys(content_type.schema.attributes).forEach((attribute) => {
const definition = content_type.schema.attributes[attribute];
// don't manage non relation attributes
if (definition.type !== 'relation') {
return;
}
if (definition.collection) {
// if a relation already exist
if (entry[attribute].length !== 0) {
return;
}
for (let index = 0; index < Faker.random.number(5); index++) {
const toAdd =
data[definition.targetModel][
Faker.random.number(data[definition.targetModel].length - 1)
];
entry[attribute].push({
id: toAdd.id,
});
}
} else if (definition.model) {
// if a relation exist of if the relation
if (
entry[attribute] !== null ||
['file', 'permission', 'role', 'administrator'].includes(definition.targetModel)
) {
return;
}
const toAdd =
data[definition.targetModel][
Faker.random.number(data[definition.targetModel].length - 1)
];
entry[attribute] = toAdd.id;
}
});
try {
await Strapi.updateEntry(content_type.uid, entry.id, content_type.source || undefined, entry);
} catch (error) {
return;
}
}
// process update all entries for a content type
async function contentTypeDataUpdate(content_type) {
const dataUpdateQueu = [];
data[content_type.uid].forEach((entry) => {
dataUpdateQueu.push(dataUpdate(entry, content_type));
});
await Promise.all(dataUpdateQueu);
}
const contentTypeDataUpdateQueu = [];
content_types.forEach(async (content_type) => {
contentTypeDataUpdateQueu.push(contentTypeDataUpdate(content_type));
});
start('Create relations');
await Promise.all(contentTypeDataUpdateQueu);
succeed();
})();