Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add script to generate/refresh demo data #250

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@

# Build Files
/build/

# Temperary Files
/tmp/
2 changes: 1 addition & 1 deletion includes/restapi/class-notification-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function authenticate() : bool {
* @return WP_REST_RESPONSE|WP_Error REST response or WP Error
*/
public function get_notifications( $request ) {
$demo_data = file_get_contents( dirname( __FILE__ ) . '/fake_api.json' );
$demo_data = file_get_contents( WP_NOTIFICATION_CENTER_PLUGIN_DIR . '/tmp/demo-data.json' );

if ( empty( $demo_data ) ) {
return new WP_Error( 'demo', __( 'Could not read demo data.' ) );
Expand Down
202 changes: 0 additions & 202 deletions includes/restapi/fake_api.json

This file was deleted.

3 changes: 2 additions & 1 deletion jsconfig.eslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
".prettierrc.js",
"babel.config.js",
"jest.config.js",
"webpack.config.js"
"webpack.config.js",
"scripts/**/*"
]
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
"wp-env:start": "wp-env start",
"wp-env:stop": "wp-env stop",
"wp-env:destroy": "wp-env destroy",
"prepare": "husky install"
"prepare": "husky install && npm run gen-demo-data",
"gen-demo-data": "node scripts/gen-demo-data.js"
},
"repository": {
"type": "git",
Expand Down
12 changes: 12 additions & 0 deletions scripts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Scripts for the WordPress Feature Notifications Project

## Generating demo data

The plugin is a demo of functionality and does not currently persist data to the WordPress database. The script to generate the demo data should be executed after running `npm install`, though the data can also be regenerated.

```sh
# to regenerate the demo data
npm run gen-demo-data
```


81 changes: 81 additions & 0 deletions scripts/gen-demo-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/* eslint-disable no-console */

const { mkdir, readFile, stat, writeFile } = require( 'node:fs/promises' );
const path = require( 'node:path' );

const { format, resolveConfig } = require( 'prettier' );

const TWO_WEEKS_IN_SECONDS = 60 * 60 * 24 * 14;

const inputPath = path.join( __dirname, 'scaffold-data.json' );
const outputPath = path.join( __dirname, '../', 'tmp', 'demo-data.json' );

main().catch( ( error ) => {
throw error;
} );

async function main() {
const prettierOptions = {
...( await resolveConfig( process.cwd() ) ),
parser: 'json',
};
const raw = await readFile( inputPath, { encoding: 'utf-8' } );
const { notices } = JSON.parse( raw );
// notices.sort( ( a, b ) => b.id - a.id); // ascending order by id
const count = notices.length;
const start = Date.now() - TWO_WEEKS_IN_SECONDS * 1000;
const dates = randomDates( new Date( start ), count );
const result = [];
for ( let i = 0; i < count; i++ ) {
const notice = notices[ i ];
const date = dates[ i ];
result.push( { ...notice, date } );
}
const stringified = JSON.stringify( result, null, 2 );
await mkdirp( path.join( __dirname, '../', 'tmp' ) );
await writeFile( outputPath, format( stringified, prettierOptions ) );
}

/**
* Generate a set of random datetime between a starting date and now.
*
* TODO check what the correct format of the notice `data` property, is it seconds?
*
* @param {Date} start The minimum value of the set of random dates.
* @param {number} count The number of dates to generate.
* @return {number[]} A set of random datetime.
*/
function randomDates( start, count ) {
const min = start.getTime();
const max = Date.now();
if ( min >= max )
throw new Error(
'The starting datetime must be less than the current time.'
);
const diff = max - min;
const result = [];
for ( let i = 0; i < count; i++ ) {
const random = Math.random() * diff;
result.push( min + random );
}
result.sort( ( a, b ) => b - a ); // descending order
return result.map( ( x ) => Math.floor( x / 1000 ) ); // convert to seconds
}
/**
* Make a directory if it doesn't exist.
*
* @param {string} filePath The path to the directory to possibly create.
* @return {void}
*/
async function mkdirp( filePath ) {
try {
const { isDirectory } = await stat( filePath );
if ( ! isDirectory() ) {
throw new Error( 'expected tmp directory is not a directory' );
}
} catch ( error ) {
if ( error.code === 'ENOENT' ) {
mkdir( filePath );
}
}
}
Loading