-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add contentful-common-strings package. (#32)
This factors out the common logic in JustFixNYC/tenants2#2125 and JustFixNYC/who-owns-what#482 into its own reusable package, `@justfixnyc/contentful-common-strings`.
- Loading branch information
Showing
16 changed files
with
826 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
!bin/cli.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
# Change Log | ||
|
||
All notable changes to this project will be documented in this file. | ||
|
||
## 0.0.1 (2021-06-24) | ||
|
||
Initial release. | ||
|
||
## 0.0.2 (2021-06-24) | ||
|
||
Weird republish because Lerna is being dumb. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
@justfixnyc/contentful-common-strings | ||
|
||
Copyright (c) JustFix.nyc. All rights reserved. | ||
|
||
MIT License | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining | ||
a copy of this software and associated documentation files (the | ||
"Software"), to deal in the Software without restriction, including | ||
without limitation the rights to use, copy, modify, merge, publish, | ||
distribute, sublicense, and/or sell copies of the Software, and to | ||
permit persons to whom the Software is furnished to do so, subject to | ||
the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be | ||
included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | ||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | ||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
This module provides tooling for retrieving and displaying common rich-text content | ||
shared by JustFix.nyc projects. | ||
|
||
Each common string has an alphanumeric id and a value. The value is a localizable | ||
rich text value. For example, the original motiviation for this package is the common | ||
string with id `covidMoratoriumBanner`, which has a value containing the rich text | ||
to show users about the current state of the COVID Moratorium, localized in both | ||
English and Spanish. | ||
|
||
This package contains tooling to retrieve all entries from a pre-configured Contentful space that have been given a particular [tag](https://www.contentful.com/help/tags/). Each of these entries is expected to have a short text field called `id` and a localized rich text field called `value`. | ||
|
||
These entries can be retrieved in one of two ways: | ||
|
||
1. A command-line program called `contentful-common-strings`. This can be useful for static sites that want to have the entries rendered at build time. | ||
|
||
2. Via the [`fetchContentfulCommonStrings`](src/fetch-common-strings.ts) function, which can be run from node or the browser. | ||
|
||
Functionality provided by the [`ContentfulCommonStrings`](src/index.ts) class makes it convenient to retrieve a common string's rich text document representation by its id. The front-end can then render them using a package like [`@contentful/rich-text-react-renderer`](https://www.npmjs.com/package/@contentful/rich-text-react-renderer). | ||
|
||
For an example of this package in use, see the [manual test][] code. | ||
|
||
To use the manual test, you can run `yarn watch` and then visit http://localhost:8080/. | ||
|
||
[manual test]: test-manual/contentful-common-strings-manual-test.tsx |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
const base = require('../../babel.config'); | ||
|
||
module.exports = { | ||
...base, | ||
presets: [ | ||
...base.presets, | ||
"@babel/preset-react", | ||
], | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
#! /usr/bin/env node | ||
|
||
const { main } = require("../dist/cli.bundle.js"); | ||
|
||
main(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
{ | ||
"name": "@justfixnyc/contentful-common-strings", | ||
"version": "0.0.2", | ||
"main": "dist/src/index.js", | ||
"types": "dist/src/index.d.ts", | ||
"license": "MIT", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/justfixnyc/justfix-ts/tree/master/packages/contentful-common-strings" | ||
}, | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"devDependencies": { | ||
"@babel/core": "7.6.4", | ||
"@babel/preset-env": "7.6.3", | ||
"@babel/preset-react": "^7.9.4", | ||
"@babel/preset-typescript": "7.6.0", | ||
"@contentful/rich-text-react-renderer": "^15.0.0", | ||
"@justfixnyc/util": "^0.3.0", | ||
"@types/jest": "24.0.15", | ||
"@types/react": "^16.9.26", | ||
"@types/react-dom": "^16.9.5", | ||
"concurrently": "^5.0.0", | ||
"http-server": "^0.12.3", | ||
"jest": "24.9.0", | ||
"react": "16.13.1", | ||
"react-dom": "16.13.1", | ||
"rollup": "^1.23.1", | ||
"rollup-plugin-commonjs": "^10.1.0", | ||
"rollup-plugin-node-resolve": "^5.2.0", | ||
"rollup-plugin-replace": "^2.2.0", | ||
"typescript": "3.6.4" | ||
}, | ||
"scripts": { | ||
"cli": "node bin/cli.js", | ||
"test": "jest", | ||
"test:watch": "jest --watch", | ||
"prepublish": "yarn build", | ||
"build": "tsc && rollup -c", | ||
"watch": "concurrently --kill-others \"tsc --watch --preserveWatchOutput\" \"rollup -c --watch\" \"http-server test-manual\"" | ||
}, | ||
"bin": { | ||
"contentful-common-strings": "./bin/cli.js" | ||
}, | ||
"dependencies": { | ||
"@contentful/rich-text-types": "^15.0.0", | ||
"cross-fetch": "^3.1.4", | ||
"yargs": "^17.0.1" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
//@ts-check | ||
import commonjs from "rollup-plugin-commonjs"; | ||
import resolve from "rollup-plugin-node-resolve"; | ||
import replace from "rollup-plugin-replace"; | ||
|
||
/** @type import('rollup').RollupWatchOptions */ | ||
const manualTestConfig = { | ||
input: "dist/test-manual/contentful-common-strings-manual-test.js", | ||
output: { | ||
format: "iife", | ||
file: "test-manual/contentful-common-strings-manual-test.bundle.js", | ||
sourcemap: "inline", | ||
}, | ||
watch: { | ||
clearScreen: false, | ||
}, | ||
plugins: [ | ||
resolve({ browser: true }), | ||
commonjs({ | ||
include: "../../node_modules/**", | ||
}), | ||
replace({ | ||
values: { | ||
"process.env.NODE_ENV": JSON.stringify("development"), | ||
}, | ||
}), | ||
], | ||
}; | ||
|
||
/** @type import('rollup').RollupWatchOptions */ | ||
const cliConfig = { | ||
input: "dist/src/cli.js", | ||
output: { | ||
format: "commonjs", | ||
file: "dist/cli.bundle.js", | ||
sourcemap: "inline", | ||
}, | ||
watch: { | ||
clearScreen: false, | ||
}, | ||
plugins: [resolve({ preferBuiltins: true }), commonjs()], | ||
external: [ | ||
"stream", | ||
"http", | ||
"url", | ||
"https", | ||
"zlib", | ||
"cross-fetch", | ||
"yargs", | ||
"fs", | ||
], | ||
}; | ||
|
||
export default [manualTestConfig, cliConfig]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import fs from "fs"; | ||
import yargs from "yargs"; | ||
import { | ||
fetchContentfulCommonStrings, | ||
DEFAULT_CONTENTFUL_COMMON_STRINGS_CONFIG as CONFIG_DEFAULTS, | ||
} from "./fetch-common-strings.js"; | ||
|
||
export function main() { | ||
yargs | ||
.scriptName("contentful-common-strings") | ||
.usage("$0 <cmd> [args]") | ||
.command( | ||
"fetch", | ||
"Fetch Contentful common strings and write them to a JSON file.", | ||
(yargs) => { | ||
yargs.option("o", { | ||
alias: "outfile", | ||
default: "--", | ||
describe: "The file to write the JSON to, or '--' to use stdout", | ||
type: "string", | ||
}); | ||
|
||
yargs.option("origin", { | ||
default: CONFIG_DEFAULTS.origin, | ||
describe: "Contentful API origin", | ||
type: "string", | ||
}); | ||
|
||
yargs.option("tag", { | ||
default: CONFIG_DEFAULTS.tag, | ||
describe: "Only entries with this Contentful tag will be retrieved", | ||
type: "string", | ||
}); | ||
|
||
yargs.option("spaceId", { | ||
default: CONFIG_DEFAULTS.spaceId, | ||
describe: "Contentful space ID", | ||
type: "string", | ||
}); | ||
|
||
yargs.option("accessToken", { | ||
default: CONFIG_DEFAULTS.accessToken, | ||
describe: "Contentful access token", | ||
type: "string", | ||
}); | ||
}, | ||
async (argv: { | ||
outfile: string; | ||
origin: string; | ||
tag: string; | ||
spaceId: string; | ||
accessToken: string; | ||
}) => { | ||
const { origin, tag, spaceId, accessToken } = argv; | ||
const map = await fetchContentfulCommonStrings({ | ||
origin, | ||
tag, | ||
spaceId, | ||
accessToken, | ||
}); | ||
const output = JSON.stringify(map, null, 2) + "\n"; | ||
if (argv.outfile === "--") { | ||
process.stdout.write(output); | ||
} else { | ||
fs.writeFileSync(argv.outfile, output); | ||
console.log(`Wrote ${argv.outfile}.`); | ||
} | ||
} | ||
) | ||
.help() | ||
.demandCommand().argv; | ||
} |
82 changes: 82 additions & 0 deletions
82
packages/contentful-common-strings/src/fetch-common-strings.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import { ContentfulCommonStringsMapping } from "."; | ||
import fetch from "cross-fetch"; | ||
|
||
/** | ||
* Configuration for fetching common strings from the Contentful API. | ||
*/ | ||
export type ContentfulCommonStringsConfig = { | ||
/** The origin of the API. */ | ||
origin: string; | ||
|
||
/** The Contentful tag to filter, if any. */ | ||
tag?: string; | ||
|
||
/** The Contentful space ID to access. */ | ||
spaceId: string; | ||
|
||
/** The Contentful access token to use. */ | ||
accessToken: string; | ||
}; | ||
|
||
/** | ||
* Sensible default configuration for JustFix projects. While | ||
* embedding the access token may appear to be a security hazard, | ||
* it's not, as the tokens provide _read-only_ access, and we | ||
* only publish public information in our Contentful spaces. | ||
*/ | ||
export const DEFAULT_CONTENTFUL_COMMON_STRINGS_CONFIG: ContentfulCommonStringsConfig = { | ||
origin: "https://cdn.contentful.com", | ||
tag: "common", | ||
spaceId: "markmr2gi204", | ||
accessToken: "Fli_OMdKgUFw6tEX3uv6HqvptuG6A6jn9bZVPlHZj8E", | ||
}; | ||
|
||
function toCommonStringsMap(raw: any): ContentfulCommonStringsMapping { | ||
const result: ContentfulCommonStringsMapping = {}; | ||
|
||
for (let item of raw.items) { | ||
const fields = item.fields; | ||
const key = fields.id && fields.id.en; | ||
const value = fields.value; | ||
if (key && value) { | ||
result[key] = value; | ||
} | ||
} | ||
|
||
return result; | ||
} | ||
|
||
function getContentfulEntriesURL( | ||
options?: Partial<ContentfulCommonStringsConfig> | ||
): string { | ||
const config = { ...DEFAULT_CONTENTFUL_COMMON_STRINGS_CONFIG, ...options }; | ||
const search = new URLSearchParams(); | ||
search.append("locale", "*"); | ||
if (config.tag) { | ||
search.append("metadata.tags.sys.id[in]", config.tag); | ||
} | ||
search.append("access_token", config.accessToken); | ||
return `${config.origin}/spaces/${ | ||
config.spaceId | ||
}/entries?${search.toString()}`; | ||
} | ||
|
||
/** | ||
* Fetch Contentful common strings over HTTPS using the given optional | ||
* configuration overrides. | ||
* | ||
* This function can be used from node or the browser. | ||
* | ||
* @see {@link DEFAULT_CONTENTFUL_COMMON_STRINGS_CONFIG} for details about | ||
* the configuration defaults. | ||
*/ | ||
export async function fetchContentfulCommonStrings( | ||
options?: Partial<ContentfulCommonStringsConfig> | ||
): Promise<ContentfulCommonStringsMapping> { | ||
const res = await fetch(getContentfulEntriesURL(options)); | ||
if (!res.ok) { | ||
throw new Error(`Contentful API returned HTTP ${res.status}`); | ||
} | ||
|
||
return toCommonStringsMap(await res.json()); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { Document as ContentfulDocument } from "@contentful/rich-text-types"; | ||
export { | ||
ContentfulCommonStringsConfig, | ||
DEFAULT_CONTENTFUL_COMMON_STRINGS_CONFIG, | ||
fetchContentfulCommonStrings, | ||
} from "./fetch-common-strings"; | ||
|
||
/** | ||
* A Contentful common string's value, available in various locales. | ||
*/ | ||
export type ContentfulCommonStringsEntry = { | ||
[locale: string]: ContentfulDocument | undefined; | ||
}; | ||
|
||
/** | ||
* A mapping from ids to values for Contentful common strings. | ||
*/ | ||
export type ContentfulCommonStringsMapping = { | ||
[id: string]: ContentfulCommonStringsEntry; | ||
}; | ||
|
||
/** | ||
* A convenience class that makes it easy to access Contentful common strings. | ||
*/ | ||
export class ContentfulCommonStrings { | ||
constructor(private readonly mapping: ContentfulCommonStringsMapping) {} | ||
|
||
/** | ||
* Return the Contentful common string with the given id in the given locale, | ||
* or `null` if it doesn't exist. | ||
*/ | ||
get(id: string, locale: string): ContentfulDocument | null { | ||
const locales = this.mapping[id]; | ||
const result = locales && locales[locale]; | ||
if (result === undefined) return null; | ||
return result; | ||
} | ||
} |
Oops, something went wrong.