Example #1
0
const getElementTextByTagNames = (
  element: Element, names: string[]
): string => {
  const e = getElementByTagNames(element, names);
  if (e === null) throw new Error(`no ${names.join('/')}`);
  const text = getText(e);
  if (text === null) throw new Error(`invalid ${names.join('/')}`);
  return text;
};
Example #2
0
const getEntry = (entry: Element): BlogEntry => {
  const elements = entry.children.filter(isElement);

  const authorName = getElementTextByTagNames(entry, ['author', 'name']);

  const contentElement = getElementByTagNames(entry, ['content']);
  if (contentElement === null) throw new Error('no content');
  if (contentElement.children.length === 0 || (
    contentElement.attributes.type !== 'text/html' &&
    contentElement.attributes.type !== 'text/x-hatena-syntax' &&
    contentElement.attributes.type !== 'text/x-markdown'
  )) throw new Error('invalid content');
  const content = getText(contentElement);
  if (content === null) throw new Error('no content text');
  const contentType = contentElement.attributes.type as BlogEntryContentType;

  const draft = getElementTextByTagNames(entry, ['control', 'draft']) === 'yes';

  const editUrlElement = elements.find((i) => {
    return getUnprefixedName(i.name) === 'link' &&
      i.attributes.rel === 'edit' &&
      typeof i.attributes.href !== 'undefined';
  });
  if (typeof editUrlElement === 'undefined') throw new Error('no edit url');
  const editUrl = editUrlElement.attributes.href;

  const edited = getElementTextByTagNames(entry, ['edited']);
  const formattedContent =
    getElementTextByTagNames(entry, ['formatted-content']);

  const htmlUrlElement = elements.find((i) => {
    return getUnprefixedName(i.name) === 'link' &&
      i.attributes.rel === 'alternate' &&
      i.attributes.type === 'text/html' &&
      typeof i.attributes.href !== 'undefined';
  });
  if (typeof htmlUrlElement === 'undefined') throw new Error('no html url');
  const htmlUrl = htmlUrlElement.attributes.href;

  const id = getElementTextByTagNames(entry, ['id']);
  const published = getElementTextByTagNames(entry, ['published']);
  const summary = getElementTextByTagNames(entry, ['summary']);
  const title = getElementTextByTagNames(entry, ['title']);
  const updated = getElementTextByTagNames(entry, ['updated']);

  return {
    authorName,
    content,
    contentType,
    draft,
    editUrl,
    edited,
    formattedContent,
    htmlUrl,
    id,
    published,
    summary,
    title,
    updated
  };
};