Skip to content

Commit

Permalink
Merge pull request #94 from viqueen/issue/v2-prep
Browse files Browse the repository at this point in the history
Issue/v2 prep
  • Loading branch information
viqueen authored Jun 22, 2024
2 parents 394bd6f + d720153 commit ca2dc90
Show file tree
Hide file tree
Showing 61 changed files with 1,580 additions and 1,479 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
*/
import { AxiosError } from 'axios';

export const axiosErrorHandler = (error: AxiosError) => {
const axiosErrorHandler = (error: AxiosError) => {
const { data, status, statusText } = error.response || {};
console.error('failed request', { data, status, statusText });
throw Error('failed request');
};

export { axiosErrorHandler };
161 changes: 161 additions & 0 deletions modules/apis/confluence/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/**
* Copyright 2023 Hasnae Rehioui
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { AxiosInstance } from 'axios';

import { environment } from '../../cli/conf';
import { axiosErrorHandler } from '../axios-error-handler';

import {
mapSearchResultItemToBlogSummary,
mapSearchResultItemToContent
} from './mappers';
import {
AttachmentData,
BlogSummary,
Content,
Identifier,
ResourceDefinition,
ResourceObject,
SearchResult
} from './types';

interface ConfluenceApi {
getSpaceHomepage(spaceKey: string): Promise<Identifier>;
getSpaceBlogs(spaceKey: string): Promise<BlogSummary[]>;
getSpaceRecentlyUpdatedPages(spaceKey: string): Promise<Identifier[]>;
getContentById(
contentId: Pick<Identifier, 'id'>,
asHomepage: boolean
): Promise<Content>;
getContentByCQL(cql: string, asHomepage: boolean): Promise<Content>;
getObjects(
resourceUrls: ResourceObject[]
): Promise<{ body: { data: ResourceDefinition } }[]>;
getAttachmentData(
targetUrl: string,
prefix: string
): Promise<AttachmentData>;
}

const confluenceApi = (client: AxiosInstance): ConfluenceApi => {
const getSpaceHomepage = async (spaceKey: string): Promise<Identifier> => {
const { data } = await client
.get(`/wiki/rest/api/space/${spaceKey}?expand=homepage`)
.catch(axiosErrorHandler);
const { homepage } = data;
const { id, title } = homepage;
return { id, title };
};

const getSpaceBlogs = async (spaceKey: string): Promise<BlogSummary[]> => {
const query = new URLSearchParams({
cql: `space=${spaceKey} and type=blogpost order by created desc`,
expand: 'content.history,content.metadata.labels,content.children.attachment.metadata.labels'
});
const { data } = await client
.get<SearchResult>(`/wiki/rest/api/search?${query.toString()}`)
.catch(axiosErrorHandler);
return data.results.map(mapSearchResultItemToBlogSummary);
};

const getSpaceRecentlyUpdatedPages = async (
spaceKey: string
): Promise<Identifier[]> => {
const query = new URLSearchParams({
cql: `space=${spaceKey} and type=page order by lastModified desc`
});
const { data } = await client
.get<SearchResult>(`/wiki/rest/api/search?${query.toString()}`)
.catch(axiosErrorHandler);
const { results } = data;
return results.map((item) => {
const { id, title } = item.content;
return { id, title };
});
};

const getContentById = async (
contentId: Pick<Identifier, 'id'>,
asHomepage: boolean
): Promise<Content> => {
return getContentByCQL(`id=${contentId.id}`, asHomepage);
};

const getContentByCQL = async (
cql: string,
asHomepage: boolean = false
): Promise<Content> => {
const contentExpansions = [
'content.body.atlas_doc_format',
'content.children.page.metadata.properties.emoji_title_published',
'content.children.attachment.metadata.labels',
'content.ancestors',
'content.history',
'content.metadata.properties.emoji_title_published',
'content.metadata.labels'
];
const query = new URLSearchParams({
cql: cql,
expand: contentExpansions.join(',')
});
const { data } = await client
.get<SearchResult>(`/wiki/rest/api/search?${query.toString()}`)
.catch(axiosErrorHandler);
const item = data.results[0];
return mapSearchResultItemToContent(item, asHomepage);
};

const getObjects = async (
resourceUrls: ResourceObject[]
): Promise<{ body: { data: ResourceDefinition } }[]> => {
const { data } = await client
.post('/gateway/api/object-resolver/resolve/batch', resourceUrls, {
headers: {
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
cookie: `cloud.session.token=${environment.CONFLUENCE_CLOUD_TOKEN}`
}
})
.catch(axiosErrorHandler);
return data;
};

const getAttachmentData = async (
targetUrl: string,
prefix: string
): Promise<AttachmentData> => {
const { data } = await client
.get(`${prefix}${targetUrl}`, {
responseType: 'stream'
})
.catch(axiosErrorHandler);
return { stream: data };
};

return {
getSpaceHomepage,
getSpaceBlogs,
getSpaceRecentlyUpdatedPages,
getContentById,
getContentByCQL,
getObjects,
getAttachmentData
};
};

export type { ConfluenceApi };
export { confluenceApi };
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,5 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const scopes = [
'read:confluence-space.summary',
'read:confluence-props',
'read:confluence-content.all',
'read:confluence-content.summary',
'search:confluence',
'read:confluence-user',
'readonly:content.attachment:confluence'
];
export * from './api';
export * from './types';
122 changes: 122 additions & 0 deletions modules/apis/confluence/mappers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/**
* Copyright 2023 Hasnae Rehioui
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import crypto from 'crypto';

import { Content, SearchResultItem, Attachment, BlogSummary } from './types';

const mapSearchResultItemToContent = (
item: SearchResultItem,
asHomepage = false
): Content => {
const { content, excerpt, lastModified } = item;
const { children, ancestors, id, title, type, body, history, metadata } =
content;

const { createdBy, createdDate } = history;
const files = children.attachment?.results || [];

const childPages =
children.page?.results.map((child) => ({
id: child.id,
title: child.title,
emoji: child.metadata.properties['emoji-title-published']?.value
})) || [];

const parentPages =
ancestors.map((parent) => ({
id: parent.id,
title: parent.title
})) || [];

const attachments = files.map(
({ extensions, _links, metadata: fileMetadata }) => ({
fileId: extensions.fileId,
downloadUrl: _links.download,
mediaType: extensions.mediaType,
isCover: fileMetadata.labels.results.some((i) => i.name === 'cover')
})
);
const author = {
id: createdBy.publicName,
title: createdBy.displayName,
accountId: crypto
.createHash('sha512')
.update(createdBy.accountId)
.digest('hex'),
avatar: createdBy.profilePicture.path
};

const cover = attachments.find((a: Attachment) => a.isCover);
const emoji = metadata.properties['emoji-title-published']?.value;

const createdAt = new Date(createdDate);

const hasPdf = metadata.labels.results.some(
(i) => i.name === 'export-to-pdf'
);

return {
author,
identifier: { id, title },
asHomepage,
excerpt,
type,
body: JSON.parse(body.atlas_doc_format.value),
lastModifiedDate: new Date(lastModified).getTime(),
createdDate: createdAt.getTime(),
createdYear: createdAt.getFullYear(),
childPages,
parentPages,
attachments,
cover,
emoji,
hasPdf
};
};

const mapSearchResultItemToBlogSummary = (
item: SearchResultItem
): BlogSummary => {
const { content, excerpt } = item;
const { id, title, type, history, children } = content;
const { createdBy, createdDate } = history;
const createdAt = new Date(createdDate);

const files = children.attachment?.results || [];
const attachments = files.map(
({ extensions, _links, metadata: fileMetadata }) => ({
fileId: extensions.fileId,
downloadUrl: _links.download,
mediaType: extensions.mediaType,
isCover: fileMetadata.labels.results.some((i) => i.name === 'cover')
})
);
const cover = attachments.find((a: Attachment) => a.isCover);
return {
identifier: { id, title },
type,
excerpt,
cover,
author: {
id: createdBy.publicName,
title: createdBy.displayName
},
createdDate: createdAt.getTime(),
createdYear: createdAt.getFullYear()
};
};

export { mapSearchResultItemToContent, mapSearchResultItemToBlogSummary };
Loading

0 comments on commit ca2dc90

Please sign in to comment.