Skip to content

Instantly share code, notes, and snippets.

@merelinguist
Created November 30, 2021 14:55
Show Gist options
  • Save merelinguist/8b5bb43e1ac77d0e648b1e6c2036877a to your computer and use it in GitHub Desktop.
Save merelinguist/8b5bb43e1ac77d0e648b1e6c2036877a to your computer and use it in GitHub Desktop.
import { getParameters } from 'codesandbox/lib/api/define';
import { IFiles } from 'codesandbox-import-utils/lib/api/define';
import { meta } from 'feature/react-hook-form/meta';
import { readdir, readFile, writeFile } from 'fs/promises';
import { GetServerSideProps, InferGetStaticPropsType } from 'next';
import { join, resolve } from 'path';
import { PackageJson } from 'types';
export const getServerSideProps: GetServerSideProps = async () => {
// Add the packages required of the feature
const packageDotJsonPath = join(process.cwd(), '_template', 'package.json');
const packageDotJson = await readFile(packageDotJsonPath, 'utf8');
if (packageDotJson) {
const json = JSON.parse(packageDotJson) as PackageJson;
json.dependencies = {
...json.dependencies,
...meta.packages.reduce(
(previousPackage, { name, version }) => ({
...previousPackage,
[name]: version,
}),
{},
),
};
// // Sort alphabetically
// json.dependencies = Object.entries(json.dependencies)
// .sort((aDependency, bDependency) =>
// aDependency[0].localeCompare(bDependency[1]),
// )
// .reduce(
// (sortedDependencies, [name, version]) => ({
// ...sortedDependencies,
// [name]: version,
// }),
// {},
// );
await writeFile(packageDotJsonPath, JSON.stringify(json, null, 2));
}
// Recursively get all the pathnames of our template
async function* getFiles(directory: string): AsyncGenerator<string> {
const entries = await readdir(directory, { withFileTypes: true });
for (const entry of entries) {
const res = resolve(directory, entry.name);
if (entry.isDirectory()) {
yield* getFiles(res);
} else {
yield res;
}
}
}
// Read all the files in the template to an object
const files: IFiles = {};
const fileNames = getFiles(join(process.cwd(), '_template'));
for await (const fileName of fileNames) {
const path = fileName.split('_template')[1];
const content = await readFile(fileName, 'utf8');
files[path] = { isBinary: false, content };
}
// Add the extra files from the feature
for (const file of meta.files) {
switch (file.type) {
case 'page':
console.log('Oranges are $0.59 a pound.');
break;
case 'router':
console.log('Mangoes and papayas are $2.79 a pound.');
break;
default:
console.log(`Sorry, we are out of ${file.type}.`);
}
console.log(file);
}
// Construct url
const parameters = getParameters({
files,
});
const url = `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}`;
return { props: { url } };
};
export default function SandboxPage({
url,
}: InferGetStaticPropsType<typeof getServerSideProps>) {
return <a href={url}>Open Sandbox</a>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment