Skip to content

Instantly share code, notes, and snippets.

@solancer
Created February 15, 2022 13:58
Show Gist options
  • Save solancer/db9532804acb0d39f922e9e1e4586870 to your computer and use it in GitHub Desktop.
Save solancer/db9532804acb0d39f922e9e1e4586870 to your computer and use it in GitHub Desktop.
crud strapi
'use strict';
const {
sanitizeEntity
} = require('strapi-utils');
const buildError = (httpStatus, payload) => {
return {
status: httpStatus,
body: JSON.stringify({
error: payload
})
}
};
/**
* Read the documentation (https://strapi.io/documentation/v3.x/concepts/controllers.html#core-controllers)
* to customize this controller
*/
module.exports = {
/**
* Retrieve records.
*
* @return {Array}
*/
async find(ctx) {
let entities;
try {
if (ctx.query._q) {
entities = await strapi.services['sku-setup'].search(ctx.query);
} else {
entities = await strapi.services['sku-setup'].find(ctx.query);
}
} catch (e) {
Object.assign(ctx, buildError(500, e.message));
ctx.set('content-type', 'application/json');
return;
}
return entities.map(entity => sanitizeEntity(entity, {
model: strapi.models['sku-setup']
}));
},
/**
* * Retrieve a record.
* *
* * @return {Object}
* */
async findOne(ctx) {
const {
id
} = ctx.params;
let entity;
try {
entity = await strapi.services['sku-setup'].findOne({
id
});
if (!entity) {
Object.assign(ctx, buildError(500, 'Not found sku-setup'));
ctx.set('content-type', 'application/json');
return;
}
} catch (e) {
Object.assign(ctx, buildError(500, e.message.replace(/"/g, '\'')));
ctx.set('content-type', 'application/json');
return;
}
return sanitizeEntity(entity, {
model: strapi.models['sku-setup']
});
},
/**
* Create a record.
*
* @return {Object}
*/
async create(ctx) {
let entity;
try {
if (ctx.is('multipart')) {
const {
data,
files
} = parseMultipartData(ctx);
entity = await strapi.services['sku-setup'].create(data, {
files
});
} else {
entity = await strapi.services['sku-setup'].create(ctx.request.body);
}
} catch (e) {
Object.assign(ctx, buildError(500, e.message.replace(/"/g, '\'')));
ctx.set('content-type', 'application/json');
return;
}
return sanitizeEntity(entity, {
model: strapi.models['sku-setup']
});
},
/**
* Update a record.
*
* @return {Object}
*/
async update(ctx) {
const {
id
} = ctx.params;
console.log('update');
let entity;
try {
if (ctx.is('multipart')) {
const {
data,
files
} = parseMultipartData(ctx);
entity = await strapi.services['sku-setup'].update({
id
}, data, {
files,
});
} else {
entity = await strapi.services['sku-setup'].update({
id
}, ctx.request.body);
}
} catch (e) {
Object.assign(ctx, buildError(500, e.message));
ctx.set('content-type', 'application/json');
return;
}
if (!entity) {
Object.assign(ctx, buildError(500, 'Not found sku-setup'));
ctx.set('content-type', 'application/json');
return;
}
return sanitizeEntity(entity, {
model: strapi.models['sku-setup']
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment