@vuesion/addon-contentful
Version:
vuesion contentful integration
84 lines (83 loc) • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const contentful_1 = require("contentful");
const _ = require("lodash");
exports.ContentfulMiddleware = (options) => {
options.defaultLocale = options.defaultLocale || 'en';
if (!options.accessToken || !options.space) {
console.warn('You have to provide "accessToken" and "space". Contentful middleware not applied.');
return (req, res, next) => {
next();
};
}
let entries;
const host = options.preview ? 'preview.contentful.com' : 'cdn.contentful.com';
const client = contentful_1.createClient({ ...options, host });
const sync = () => {
client
.getEntries({ content_type: 'page', include: 6, locale: '*' })
.then((contentTypes) => (entries = contentTypes.items))
.catch((e) => console.error(e));
};
sync();
setInterval(() => sync(), options.syncIntervalInSeconds * 1000 || 300000);
const getLocaleValue = (item, locale) => {
if (item[locale]) {
return item[locale];
}
return item[options.defaultLocale];
};
const getProperties = (item, locale) => {
const properties = {};
Object.keys(item.fields).forEach((key) => {
const value = getLocaleValue(item.fields[key], locale);
if (_.isArray(value)) {
properties[key] = value.map((entry) => {
const prop = {};
Object.keys(entry.fields).forEach((k) => {
prop[k] = getLocaleValue(entry.fields[k], locale);
});
return prop;
});
}
else {
properties[key] = value;
}
});
return properties;
};
const transformContentfulPageToVue = (page, locale) => {
if (!page) {
return null;
}
return {
slug: getLocaleValue(page.fields.slug, locale),
title: getLocaleValue(page.fields.title, locale),
metaDescription: getLocaleValue(page.fields.metaDescription, locale),
contentItems: getLocaleValue(page.fields.contentItems, locale).map((item) => {
return {
component: item.sys.contentType.sys.id,
properties: getProperties(item, locale),
};
}),
};
};
return (req, res) => {
const slug = req.query.slug || '/';
const locale = req.query.locale;
const entry = entries.find((p) => getLocaleValue(p.fields.slug, locale) === slug);
let page;
try {
page = transformContentfulPageToVue(entry, locale);
}
catch (e) {
page = null;
}
if (page) {
res.status(200).json(page);
}
else {
res.status(404).json({ message: 'not found' });
}
};
};