fetch wrapper

This commit is contained in:
shibafu
2020-08-06 02:26:51 +09:00
parent 081dd8da28
commit 422891e237
4 changed files with 106 additions and 34 deletions

View File

@@ -1,3 +1,5 @@
import { fetchGet } from './fetch';
(function ($) {
$.fn.linkCard = function (options) {
const settings = $.extend(
@@ -9,43 +11,44 @@
return this.each(function () {
const $this = $(this);
$.ajax({
url: settings.endpoint,
method: 'get',
type: 'json',
data: {
url: $this.find('a').attr('href'),
},
}).then(function (data) {
const $metaColumn = $this.find('.col-12:last-of-type');
const $imageColumn = $this.find('.col-12:first-of-type');
const $title = $this.find('.card-title');
const $desc = $this.find('.card-text');
const $image = $imageColumn.find('img');
if (data.title === '') {
$title.hide();
} else {
$title.text(data.title);
}
const url = $this.find('a').attr('href');
if (!url) {
return;
}
if (data.description === '') {
$desc.hide();
} else {
$desc.text(data.description);
}
fetchGet(settings.endpoint, { url })
.then((response) => response.json())
.then((data) => {
const $metaColumn = $this.find('.col-12:last-of-type');
const $imageColumn = $this.find('.col-12:first-of-type');
const $title = $this.find('.card-title');
const $desc = $this.find('.card-text');
const $image = $imageColumn.find('img');
if (data.image === '') {
$imageColumn.hide();
$metaColumn.removeClass('col-md-6');
} else {
$image.attr('src', data.image);
}
if (data.title === '') {
$title.hide();
} else {
$title.text(data.title);
}
if (data.title !== '' || data.description !== '' || data.image !== '') {
$this.removeClass('d-none');
}
});
if (data.description === '') {
$desc.hide();
} else {
$desc.text(data.description);
}
if (data.image === '') {
$imageColumn.hide();
$metaColumn.removeClass('col-md-6');
} else {
$image.attr('src', data.image);
}
if (data.title !== '' || data.description !== '' || data.image !== '') {
$this.removeClass('d-none');
}
});
});
};