fix: Use friendly urls for collections (#2162)

Co-authored-by: Tom Moor <tom.moor@gmail.com>
This commit is contained in:
Saumya Pandey
2021-06-10 06:18:48 +05:30
committed by GitHub
parent a6d4d4ea36
commit 6beb6febc4
19 changed files with 243 additions and 112 deletions

View File

@ -1,13 +1,13 @@
// @flow
import { find, findIndex, concat, remove, uniq } from "lodash";
import randomstring from "randomstring";
import slug from "slug";
import isUUID from "validator/lib/isUUID";
import { SLUG_URL_REGEX } from "../../shared/utils/routeHelpers";
import { Op, DataTypes, sequelize } from "../sequelize";
import slugify from "../utils/slugify";
import CollectionUser from "./CollectionUser";
import Document from "./Document";
slug.defaults.mode = "rfc3986";
const Collection = sequelize.define(
"collection",
{
@ -72,7 +72,9 @@ const Collection = sequelize.define(
},
getterMethods: {
url() {
return `/collections/${this.id}`;
if (!this.name) return `/collection/untitled-${this.urlId}`;
return `/collection/${slugify(this.name)}-${this.urlId}`;
},
},
}
@ -223,6 +225,17 @@ Collection.addHook("afterCreate", (model: Collection, options) => {
// Class methods
Collection.findByPk = async function (id, options = {}) {
if (isUUID(id)) {
return this.findOne({ where: { id }, ...options });
} else if (id.match(SLUG_URL_REGEX)) {
return this.findOne({
where: { urlId: id.match(SLUG_URL_REGEX)[1] },
...options,
});
}
};
// get all the membership relationshps a user could have with the collection
Collection.membershipUserIds = async (collectionId: string) => {
const collection = await Collection.scope("withAllMemberships").findByPk(