Skip to content

Commit

Permalink
Merge pull request #11 from weseek/feat/tc2023e-38-add-pages-endpoint
Browse files Browse the repository at this point in the history
Feat/tc2023e-38 add pages endpoint
  • Loading branch information
atsuki-t authored Oct 12, 2023
2 parents f9e14a2 + b9c5038 commit 9258900
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 23 deletions.
63 changes: 51 additions & 12 deletions apps/app/src/server/routes/cms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import emoji from 'markdown-it-emoji';

import loggerFactory from '~/utils/logger';

const ApiResponse = require('../util/apiResponse');

const logger = loggerFactory('growi:routes:cms:pages');

module.exports = function(crowi) {
Expand All @@ -13,28 +15,65 @@ module.exports = function(crowi) {

actions.api = api;

/**
* @api {get} /pages.get get pages
* @apiName get
* @apiGroup Page
*
* @apiParam {String} id
*/
api.list = async function(req, res) {
// const nameSpace = req.params.nameSpace;
const limit = parseInt(req.query.limit) || 50;
const offset = parseInt(req.query.offset) || 0;

const queryOptions = { offset, limit: limit + 1 };

// if (nameSpace == null) {
// return res.json(ApiResponse.error('Parameter nameSpace is required.'));
// }

let pages;

try {
// TODO: namespace を考慮する
const result = await Page.findListByStartWith('', undefined, queryOptions);

// TODO: latestRevisionData が付いている pages を、1つずつではなくまとめて取得する
pages = await Promise.all(result.pages.map(async(page) => {
const reGetPage = await Page.findByIdAndViewer(page._id);
reGetPage.initLatestRevisionField(undefined);
return reGetPage.populateDataToShowRevision();
}));
}
catch (err) {
logger.error('get-pages-failed', err);
return res.json(ApiResponse.error(err));
}

if (pages.length > limit) {
pages.pop();
}

const pagesWithHTMLString = pages.map((page) => {
return { page, htmlString: md({ html: true, linkify: true }).use(emoji).render(page.revision.body) };
});

return res.json(ApiResponse.success(pagesWithHTMLString));
};

api.get = async function(req, res) {
const pageId = req.params.pageId;

if (pageId == null) {
return res.json(ApiResponse.error('Parameter pageId is required.'));
}

let page;

try {
page = await Page.findByIdAndViewer(pageId);
}
catch (err) {
logger.error('get-page-failed', err);
return res.apiv3Err(err, 500);
return res.json(ApiResponse.error(err));
}

if (page == null) {
return res.apiv3Err('Page is not found', 404);
return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`));
}

if (page != null) {
Expand All @@ -46,13 +85,13 @@ module.exports = function(crowi) {
}
catch (err) {
logger.error('populate-page-failed', err);
return res.apiv3Err(err, 500);
return res.json(ApiResponse.error('Populate page failed'));
}
}

const htmlString = md({ html: true }).use(emoji).render(page.revision.body);
const htmlString = md({ html: true, linkify: true }).use(emoji).render(page.revision.body);

return res.apiv3({ ...page, htmlString });
return res.json(ApiResponse.success({ page, htmlString }));
};

return actions;
Expand Down
1 change: 1 addition & 0 deletions apps/app/src/server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ module.exports = function(crowi, app) {

app.use('/ogp', express.Router().get('/:pageId([0-9a-z]{0,})', loginRequired, ogp.pageIdRequired, ogp.ogpValidator, ogp.renderOgp));

app.get('/_cms/list.json', cms.api.list);
app.get('/_cms/:pageId.json', cms.api.get);
app.get('/_cms/tags', tag.api.list);

Expand Down
1 change: 1 addition & 0 deletions apps/mobliz-clone/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
NEXT_PUBLIC_APP_SITE_URL=http://localhost:3000
2 changes: 1 addition & 1 deletion apps/mobliz-clone/src/pages/[pageId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const DetailPage: NextPage<Props> = (props: Props) => {
const [error, setError] = useState<string>();

useEffect(() => {
axios.get(`http://localhost:3000/_cms/${pageId}.json`)
axios.get(`${process.env.NEXT_PUBLIC_APP_SITE_URL}/_cms/${pageId}.json`)
.then((response) => {
setHTMLString(response.data.htmlString);
})
Expand Down
56 changes: 46 additions & 10 deletions apps/mobliz-clone/src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,56 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';

import parse from 'html-react-parser';
import { NextPage } from 'next';

import axios from '~/utils/axios';

const Top: NextPage = () => {
const [body, setBody] = useState<string>();
axios.get('http://localhost:3000/_api/v3/page?pageId=6522505d8eddc4a6c69499b0').then((data) => {
setBody(data.data.page.revision.body);
});
const TopPage: NextPage = () => {
const [data, setData] = useState<any[]>();
const [error, setError] = useState<string>();

useEffect(() => {
axios.get(`${process.env.NEXT_PUBLIC_APP_SITE_URL}/_cms/list.json`)
.then((response) => {
setData(response.data);
})
.catch((error) => {
setError(`データの取得に失敗しました。\n${JSON.stringify(error)}`);
});
}, []);

return (
<div className="border bg-white p-5">
<pre>{body}</pre>
</div>
<>
{error == null ? (
<>
{data == null ? (
<div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div>
) : (
<>
{data.map((pageData, index) => {
return (
<div className={`border bg-white p-5${index === 0 ? '' : ' mt-5'}`}>
<div className="index-preview overflow-hidden">
{parse(pageData.htmlString)}
</div>
<a href={`/${pageData.page._id}`} className="btn btn-outline-primary text-decoration-none rounded-0 mt-4">
続きを読む
</a>
</div>
);
})}
</>
)}
</>
) : (
<div className="border bg-white p-5">
<p>{error}</p>
</div>
)}
</>
);
};

export default Top;
export default TopPage;
8 changes: 8 additions & 0 deletions apps/mobliz-clone/src/styles/globals.scss
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,11 @@ a {
text-decoration: underline;
}
}

img {
max-width: 100%;
}

.index-preview {
max-height: 500px;
}

0 comments on commit 9258900

Please sign in to comment.